C++では stringクラスとwstringクラスの2種類が標準で組み込まれています。この2種類を使って相互変換をします。
また、System.Runtime.InteropServices名前空間のMarshalクラスも使います。
std::string mbStr = "マルチバイト文字列";
std::string ucStr = L"ユニコード文字列";
//char*をString^に変換
String^ ret = gcnew String(mbStr.data(), 0, mbStr.length);
//wchar_t*をString^に変換
String^ ret = gcnew String(ucStr,data(), 0, ucStr.length);
//String^をchar*に変換
String^ text = "ドットネット文字列";
IntPtr mptr = Marshal::StringToHGlobalAnsi(text);
std::string ret = static_cast(mptr.ToPointer());
Marshal::FreeHGlobal(mptr);
//String^をwchar_t*に変換
String^ text = "ドットネット文字列";
IntPtr mptr = Marshal::StringToHGlobalUni(text);
std::wstring ret = static_cast(mptr.ToPointer());
Marshal::FreeHGlobal(mptr);
#using
#include
#include
using namespace System;
using namespace System::Runtime::InteropServices;
public ref class PrintTest
{
public:
static void ShowMsg(String^ msg)
{
IntPtr mptr = Mashal::StringToHGlobal(msg);
std::string ret = static_cast(mptr.ToPointer());
printf("%s\n", ret.c_str() );
Marshal::FreeHGlobal(mptr);
}
};
int main(array^ args)
{
String^ text = gcnew String("こんにちは");
PrintTest::ShowMsg(text);
return 0;
}