Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert between char* and System::String in C++/CLI

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"?

like image 797
Brian Stewart Avatar asked Sep 11 '08 13:09

Brian Stewart


2 Answers

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); 
like image 71
Ben Straub Avatar answered Oct 16 '22 07:10

Ben Straub


There's a good overview here (this marshaling support added for VS2008): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx

like image 37
Matthew Clendening Avatar answered Oct 16 '22 08:10

Matthew Clendening