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.
The reason the
std::stringversion works is because it immediately creates a privatecopy of thechar*value. This private copy is not affected by the laterFreeHGlobal.The
char*version is assigned a pointer to memory which you then free on the very next line. It’s invalid the moment theFreeHGlobalcommand executes.