Bri*_*art 42 .net string c++-cli
什么是从char*转换为System :: string并返回C++/CLI的批准方式是什么?我在Google上发现了一些对marshal_to <>模板化函数的引用,但看起来这个功能从来没有为Visual Studio 2005做过(而且在Visual Studio 2008中也没有,AFAIK).我还在Stan Lippman的博客上看到了一些代码,但它是从2004年开始的.我还看过Marshal :: StringToHGlobalAnsi().有没有一种被认为是"最佳实践"的方法?
Ben*_*aub 73
System :: String有一个带char*的构造函数:
using namespace system;
const char* charstr = "Hello, world!";
String^ clistr = gcnew String(charstr);
Console::WriteLine(clistr);
Run Code Online (Sandbox Code Playgroud)
获得一个char*会更难,但也不会太糟糕:
IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
char *pNewCharStr = static_cast<char*>(p.ToPointer());
cout << pNewCharStr << endl;
Marshal::FreeHGlobal(p);
Run Code Online (Sandbox Code Playgroud)
小智 18
这里有一个很好的概述(为VS2008添加了这个编组支持):http: //www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx