C++/CLI字符串转换

Dav*_*vid 2 string interop c++-cli stdstring visual-c++

我发现这个非常好的代码片段将字符串转换为System:String^如下:

System::String^ rtn = gcnew String(move.c_str());  // 'move' here is the string
Run Code Online (Sandbox Code Playgroud)

我正在将rtn传递给C#程序.无论如何,在这个代码存在的函数内部,我传入了一个System::String^.我还发现了一些System:String^使用以下代码将a转换为字符串的代码:

pin_ptr<const wchar_t> wch = PtrToStringChars(cmd);  // 'cmd' here is the System:String          
size_t convertedChars = 0;
size_t  sizeInBytes = ((cmd->Length + 1) * 2);
errno_t err = 0;
char *ch = (char *)malloc(sizeInBytes);

err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes);
Run Code Online (Sandbox Code Playgroud)

现在我可以使用'ch'作为字符串.

然而,这似乎比使用其他方式转换更多的工作gcnew.所以,最后我的问题是,是否有一些东西将System::String^使用与gcnew方式类似的方式将a转换为字符串?

ild*_*arn 10

使用VC++的编组库:C++中的Marshaling概述

#include <msclr/marshal_cppstd.h>

// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
Run Code Online (Sandbox Code Playgroud)

  • @harsha:`std :: string`有一个析构函数可以释放它的内部分配,因此代码是完全安全的. (2认同)