在C++/CLI中转换char*和System :: String的最佳方法是什么

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)

  • 与Marsrs提到的`marshal_context`相比,Marshal :: StringToHGlobalAnsi`是一个糟糕的选择,它使用RAII自动释放缓冲区.更不用说名称是完全错误的,它根本不会返回"HGLOBAL". (6认同)
  • +1,System :: String构造函数也需要长度和编码! (5认同)

小智 18

这里有一个很好的概述(为VS2008添加了这个编组支持):http: //www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx

  • 谢谢,但这是一个冗长的解释.这更加重要:`#include <msclr\marshal.h> // marshal_context context; // my_c_string = context.marshal_as <const char*>(my_csharp_string);` (7认同)