问题描述
我想在Visual C ++环境中将std :: string转换为System :: String ^。我知道我们可以通过 MarshalString
函数将System :: String转换为std :: string:
I want to convert to std::string to System::String^ in Visual C++ environment. I know that we can convert System::String to std::string by the MarshalString
Function as below:
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));
}
$ b $ p我找不到将std :: string转换为System的方法: :String但我发现System :: String的构造函数带有如下的参数:
I can't find the way to convert std::string to System::String but I found that System::String has constructor with argument as below :
System::String(Char* value, Int32 startIndex, Int32 length)
我尝试使用下面的代码,但它不能给我正确的解决方案:
and i try to use code like below, but it can not give me a correct solution :
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
我的代码发生了什么错误?
What wrong happen in my code?
推荐答案
Microsoft提供与Visual Studio,以促进C ++和C ++ / CLI之间的交互。该库提供了,它会将 std :: string
转换为 System :: String ^
给您:
Microsoft provide their C++ Suppport Library with Visual Studio to facilitate interaction between C++ and C++/CLI. That library provides the template function marshal_as
which will convert a std::string
to a System::String^
for you:
#include <msclr\marshal_cppstd.h>
std::string stdString;
System::String^ systemString = msclr::interop::marshal_as<System::String^>(stdString);
这篇关于将标准C ++字符串转换为String ^的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!