convert standard C++ string to String^

家住魔仙堡 提交于 2019-11-27 19:38:30

问题


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:


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


来源:https://stackoverflow.com/questions/8604577/convert-standard-c-string-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!