Jean-Luc
Jean-Luc

Reputation: 3613

converting from system::String to std::string

To convert from a system::String to an std::string, I use the following code:

IntPtr p = Marshal::StringToHGlobalAnsi(PORT);
string newString = static_cast<char*>(p.ToPointer());
Marshal::FreeHGlobal(p);

However, the place where I got the code uses

IntPtr p = Marshal::StringToHGlobalAnsi(PORT);
char* newString = static_cast<char*>(p.ToPointer());
Marshal::FreeHGlobal(p);

For some reason though, I get garbage in newString if I do the char* version. Anyone know why this would happen?

Thanks.

Upvotes: 2

Views: 337

Answers (2)

PH Mohmmed Alaa
PH Mohmmed Alaa

Reputation: 1

you can Returns a pointer to an array that contains a null-terminated sequence of characters with std::string::c_str then initialize the String^ with the char array

std::string bla = "ConvertMe";
String^ ResultString= gcnew String(bla.c_str());

Upvotes: 0

JaredPar
JaredPar

Reputation: 755587

The reason the std::string version works is because it immediately creates a privatecopy of the char* value. This private copy is not affected by the later FreeHGlobal.

The char* version is assigned a pointer to memory which you then free on the very next line. It's invalid the moment the FreeHGlobal command executes.

Upvotes: 4

Related Questions