今週のキャリッジさん

とある銀座の零細システム会社の社員ブログ

アンマネージとマネージとカオス

12月 24th, 2009

こんばんは。
今日はアンマネージな型とマネージな型の間で、値を変換して遣り取りするコードを書いてみた。
今やってる仕事で、アンマネージコードとマネージコードが混合してるソースを書いてるから備忘録のつもりでカキカキと。
簡単な所でstd::string とSystem::Stringをご紹介。

まず、std::stringをSystem::Stringに変換してみる。
こいつは簡単。
System::Stringのコンストラクタに放り込むだけ。

[std::string → System::String]
System::System^ func1( std::string str )
{
return gcnew System::String( str.c_str() );
}

お次は、System::Stringをstd::stringに変換。
こっちはちょいと面倒です。
こいつを実現する方法の一つがMarshalクラスを利用する方法。
MarshalクラスのStringToHGlobalAnsiメソッドを使ってSystem::Stringのアンマネージなポインタを取得。
取得したポインタをstatic_castでstd::stringにキャストして放り込む。
んで、ポインタの後始末。

[System::String → std::string]
std::string func2( System::String^ str )
{
IntPtr ptr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi( str );
string ret = static_cast<const char*>( ptr.ToPointer() );
System::Runtime::InteropServices::Marshal::FreeCoTaskMem( ptr );
return ret;
}

上記を応用するとarray<String^> → vector<string> 変換とかも出来ます。
昔の資産を利用しなきゃいけない場合、共通機能としていくつか変換関数を作っておくと便利ですな。

Leave a Reply