convert standard C++ string to String^

2019-02-27 17:49发布

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));
}

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?

1条回答
你好瞎i
2楼-- · 2019-02-27 18:48

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);
查看更多
登录 后发表回答