System:Stringを色々な型に変換

これは何?

System:Stringを色々な型に変換するサンプルコードです。

経緯

VisualC++のwindowsFormでは、テキストボックスの入力値の型はSystem:String。
System:Stringは加工が面倒。
なので、System:Stringを色々な型に変換するユーティリティがあると便利と思い作成。

ポイント

注意点

アンマネージドコードを使っているので、/clr:pure では使えないと思います。

ソース

class Util{
	// System::String → char*
	static const char* systemStringToChar(System::String^ systemStr)
	{
		using namespace System;
		using namespace System::Runtime::InteropServices;

		// 文字コードは、環境に合わせる(普通はUTF-8)
		int len = Syetem::text::Encoding::getEncoding("UTF-8")->GetbyteCount(systemStr);
		if( len > 0 ){
			char* rtnSts = new char[len+1];
			memset(rtnSts, 0x00, sizeof(char)*len+1);
			const char* buf = static_cast<const char*>((Marshal::StringToHGlobalAnsi(systemStr)).ToPointer());
			// 取得した文字列をコピー
			strncpy_s(rtnSts, len+1, buf, _TRUNCATE);
			// メモリ開放
			Marshal::FreeHGlobal(IntPtr((void*)buf));
			return rtnSts;
		}
		return NULL;
	}

	// System::String → std::string
	static std::string systemStringToStdString(System::String ^ s) {
		using namespace System::Runtime::InteropServices;

		IntPtr hString = Marshal::StringToHGlobalAnsi(s);
		if (hString == 0) return ””;

		std::string rtnSts = (const char *)hString.ToPointer();
		Marshal::FreeHGlobal(hString);
		return rtnSts;
	}

	// System::String → int
	static int systemStringToInt(System::String^ systemStr)
	{
		using namespace System;
		using namespace System::Runtime::InteropServices;
		const char* chars = systemStringToChar(systemStr);
		// NULLだったら0を返す
		int rtnSts = 0;
		if( chars != NULL ){
			rtnSts = atoi(chars);
		}
		delete chars;
		return rtnSts;
	}

	// System::String → _int64
	static _int64 systemStringToInt64(System::String^ systemStr)
	{
		using namespace System;
		using namespace System::Runtime::InteropServices;
		const char* chars = systemStringToChar(systemStr);
		// NULLだったら0を返す
		_int64 rtnSts = 0;
		if( chars != NULL ){
			rtnSts = _atoi64(chars);
		}
		delete chars;
		return rtnSts;
	}
}

追記

追記がごちゃごちゃしてきたので整理。
miaさんのアドバイスで、大分すっきりしたコードになりました。謝恩。

2007/10/18追記

2バイト文字の場合、systemStr->Length;だと正しく文字数が取得できない不具合修正。
参考した方申し訳ありませんでした。
また、id:binnMTIさんの■[統合開発環境]Visual C++ 2008 Express Edition Beta 2 日本語版より、VC2008では一部キャストが必要との事でした。


id:binnMTIさん情報感謝です。


そんなかんじー。