views:

5163

answers:

3

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

+1  A: 

What we did is made a C++\CLI object that held the string in unmangaed code and would give out manged copies of the item. The conversion code looks very much like what Stan has on his blog (I can't remember it exactly)(If you use his code make sure you update it to use delete[]) but we made sure that the destructor would handle releasing all the unmanged elements of the object. This is a little overblown but we didn't have leaks when we tied into legacy C++ code modules.

Dan Blair
+4  A: 

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

Matthew Clendening
+9  A: 

System::String has a constructor that takes a char*:

 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);
Ben Straub
+1, System::String constructor also takes length and encoding!
Anton