2011-12-22 53 views
1

Visual C++環境でstd :: stringからSystem :: String ^に変換します。私は、システムへのstd ::文字列を変換する方法を見つけることができません標準の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)); 
} 

::文字列が、私が見つかりました:私は以下のようにMarshalString機能別の文字列::文字列はstdする::私たちは、システムを変換することができることを知っていますそのシステム::文字列は以下のように引数を持つコンストラクタを持っています

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

コードの2枚が同じ事やっていません: 'MarshalString'はwstring'' 'に文字列^ S'に変換し、あなたのスニペットは 'string'から' String^s'に変換されます(逆の場合)。 – dasblinkenlight

+1

あなたの試みの問題は、 'System :: Char'は16ビットの値ですが、' char'はVisual C++が8ビットの値であることです。 –

答えて

6

マイクロソフトでは、Visual StudioにC++ Suppport Libraryを提供しており、C++とC++/CLIのやりとりを容易にしています。そのライブラリはあなたのためにSystem::String^std::stringを変換するテンプレート機能marshal_asを提供しています。

#include <msclr\marshal_cppstd.h> 

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