Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

visual c++ - convert standard C++ string to 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));
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <msclrmarshal_cppstd.h>

std::string stdString;
System::String^ systemString = msclr::interop::marshal_as<System::String^>(stdString);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...