1
我想在Visual C++环境中将std :: string转换为System :: String ^。我知道,我们可以转换系统::字符串到std ::通过如下的MarshalString
功能串:将标准C++字符串转换为字符串^
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(Char* value, Int32 startIndex, Int32 length)
,我尝试使用类似的代码下面,但它不能给我一个正确的解决办法:
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
什么错误发生在我码?
的两段代码都没有做同样的事情:''MarshalString'字符串^ s'转换为'wstring',而你的代码片段从'string'转换为'String^s'(换句话说)。 – dasblinkenlight 2011-12-22 13:36:44
你的尝试的问题是'System :: Char'是一个16位的值,但'char'是Visual C++是一个8位的值。 – 2011-12-22 14:48:12