2011-12-22 106 views
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()); 

什麼錯誤發生在我碼?

+0

的兩段代碼都沒有做同樣的事情:''MarshalString'字符串^ s'轉換爲'wstring',而你的代碼片段從'string'轉換爲'String^s'(換句話說)。 – dasblinkenlight 2011-12-22 13:36:44

+1

你的嘗試的問題是'System :: Char'是一個16位的值,但'char'是Visual C++是一個8位的值。 – 2011-12-22 14:48:12

回答

6

Microsoft在Visual Studio中提供了它們的C++ Suppport Library以促進C++和C++/CLI之間的交互。該庫提供了模板功能marshal_as這將轉化爲你std::stringSystem::String^

#include <msclr\marshal_cppstd.h> 

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