string - C++/CLI 字符串转换

标签 string visual-c++ c++-cli interop stdstring

我发现这段非常好的代码可以将字符串转换为 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/

相关文章:

c# - 无法将类型 'System.ValueType' 隐式转换为 'int?'

c# - 在 C# 中使用 Regex 提取 Form 标记中的操作属性?

arrays - 如何在 Rust 中将一串数字转换为数组或整数向量?

java - 机器人一遍又一遍地打印相同的字符串

c++ - 如何#include 在 C++/CLI 项目中使用 nullptr 的第三方 native C++ header

.net - "Value does not fall within expected range"在运行时错误中是什么意思?

java - java中字符串的拆分问题

c++ - Microsoft Visual C++ 6.0 破坏项目

c++ - 确定动态库是否存在的多平台方法

c++ - mingw和msvc之间的这种差异是否正常