What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?
System::String has a constructor that takes a char*:
using namespace system; const char* charstr = "Hello, world!"; String^ clistr = gcnew String(charstr); Console::WriteLine(clistr);
Getting a char* back is a bit harder, but not too bad:
IntPtr p = Marshal::StringToHGlobalAnsi(clistr); char *pNewCharStr = static_cast<char*>(p.ToPointer()); cout << pNewCharStr << endl; Marshal::FreeHGlobal(p);
There's a good overview here (this marshaling support added for VS2008): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With