【发布时间】:2012-01-26 03:15:51
【问题描述】:
我想在 Visual C++ 环境中将 std::string 转换为 System::String^。我知道我们可以通过MarshalString 函数将 System::String 转换为 std::string 如下:
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
我找不到将 std::string 转换为 System::String 的方法,但我发现 System::String 的构造函数具有如下参数:
System::String(Char* value, Int32 startIndex, Int32 length)
我尝试使用下面的代码,但它不能给我一个正确的解决方案:
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
我的代码出了什么问题?
【问题讨论】:
-
这两段代码没有做同样的事情:
MarshalString将String ^ s转换为wstring,而您的sn-p 从string转换为String ^ s(即另一个方式)。 -
您尝试的问题是
System::Char是 16 位值,但char是 Visual C++ 是 8 位值。
标签: string visual-c++ c++-cli stdstring