Newbie: String conversion

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Hi,

Firstly, let me apologise if this is asked all the time, I couldn't find an
answer on Google groups.

Anyway, how do I convert a System::String to a std::string?? I have some
libraries which use std::strings and was trying to use them with VCE 2005.
Also, any worthwhile books out for VC 05 yet?

Many thanks for any advice.
 
Fredrik Wahlgren said:

Hi, I am trying to do the opposite by converting from a std::string to a
System::String in VC++ Express Beta but the solution shown in the link above
does not seem to work

Marshal::PtrToStringAnsi((int*) stl.c_str());

I get the following error:
error C2665: 'System::Runtime::InteropServices::Marshal::PtrToStringAnsi' :
none of the 2 overloads could convert all the argument types stdafx.cpp:
could be 'System::String^
System::Runtime::InteropServices::Marshal::PtrToStringAnsi(System::IntPtr)'
while trying to match the argument list '(int *)'

And I can't cast to a System::IntPtr...

Anyone have any solutions to this? Would be much appreciated
 
teNka said:
Hi, I am trying to do the opposite by converting from a std::string
to a System::String

std::string unmanaged("foobar");
System::String^ managed=new System::String(unmanaged.c_str());

Arnaud
 
Fredrik said:

I could never understand this Marshal, casts, etc non-sense.


At first String contains wchar_ts (System::Char) so the ISO C++ suitable
type for this purpose is wstring.


We can copy character by character the String to a wstring by using
String::Chars, String::Length and wstring::push_back().

An example with managed extensions:


#using <mscorlib.dll>

#include <string>


int main()
{
using namespace System;

using namespace std;

String *p= S"Test string";

wstring s;

for(long i=0; i<p->Length; ++i)
s.push_back(p->Chars);


Console::WriteLine(s.c_str());
}



Using C++/CLI and String with stack semantics and operator[]:


#include <string>


int main()
{
using namespace System;

using namespace std;

String ms= "Test string";

wstring s;

for(long i=0; i<ms.Length; ++i)
s.push_back(ms);


Console::WriteLine(s.c_str());
}


It compiles and crashes. Just filled it as a bug with subject:

"System::String default indexed property bug".



Naturally one can use other approaches like String::ToCharArray() etc.
 
Arnaud Debaene said:
std::string unmanaged("foobar");
System::String^ managed=new System::String(unmanaged.c_str());

Sorry to be pedantic, but this won't work in the (admittedly rare) case
where the string contains embedded null characters. Better is this:

System::String^ managed=new System::String(unmanaged.c_str(), 0,
unmanaged.length());
 
Back
Top