我发现这段非常好的代码可以将字符串转换为 System:String^
,如下所示:
System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string
我正在将 rtn 传回 C# 程序。不管怎样,在这个代码所在的函数内部,我传入了一个 System::String^
。我还找到了一些使用以下代码将 System:String^
转换为字符串的代码:
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);
现在我可以将“ch”用作字符串。
然而,这似乎比使用 gcnew
转换其他方式要多得多。所以,最后我的问题是,有没有什么东西可以使用与 gcnew 方式类似的方式将 System::String^
转换为字符串?
最佳答案
使用 VC++ 的编码库:Overview of Marshaling in C++
#include <msclr/marshal_cppstd.h>
// given System::String^ mstr
std::string nstr = msclr::interop::marshal_as<std::string>(mstr);
关于string - C++/CLI 字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179451/