Click to See Complete Forum and Search --> : System::String to std::string


lmoreault
February 22nd, 2008, 01:44 PM
Hi,

I have made a few searches on the board and in google but I can't seem to find an answer to my question.

I wanted to know if there was an easy way to convert a managed string (System::String) to an unmanaged one (std::string) ?

Thank you very much.

darwen
February 22nd, 2008, 01:59 PM
There are a few ways of doing this.

You can use methods in the System::Runtime::InteropSerices::Marshal class e.g.


IntPtr bufferx = System::Runtime::InteropServices::Marshal::StringToCoTaskMemAnsi(myString);
std::string stdString2(reinterpret_cast<char *>(bufferx.ToPointer()));
System::Runtime::InteropServices::Marshal::FreeCoTaskMem(bufferx);


Or since std::string is 8-bit whereas String is 16-bit, so you have to do it via a unicode-to-ascii conversion e.g.


array<unsigned char> ^buffer = System::Text::Encoding::ASCII->GetBytes(myString);
pin_ptr<unsigned char> pBuffer = &buffer[0];
std::string stdString(reinterpret_cast<char *>(pBuffer));


The second is my preference because it enables you to specify a codepage if you need to by doing the following :


const int WesternEuropeanCodePage = 1252;

String ^myString = "hello there";
array<unsigned char> ^buffer =
System::Text::Encoding::ASCII->GetEncoding(WesternEuropeanCodePage)->GetBytes(myString);
pin_ptr<unsigned char> pBuffer = &buffer[0];
std::string stdString(reinterpret_cast<char *>(pBuffer));


Also, it doesn't require any explicit memory cleanup which the first method does (the call to FreeCoTaskMem).

Darwen.

lmoreault
February 22nd, 2008, 02:31 PM
Thank you very much darwen I used the first solution using Marshalling and it seems to work perfectly.