2009年7月13日 星期一

visual C++的String^, std::string, char *的互相轉換

Unmanaged to Managed: ------------------------------------ char* su; String^ sm = gcnew String(su); wchar_t* su; String^ sm = gcnew String(su); std::string su; String^ sm = gcnew String(su.c_str()); std::wstring su; String^ sm = gcnew String(su.c_str()); Managed to Unmanaged: ------------------------------------ Wide string version: String^ sm = "Hello"; pin_ptr pu = PtrToStringChars(sm); // PtrToStringChars is an inline function in vcclr.h, and it returns // a raw pointer to the internal representation of the String. // After pinning "p", it can be passed to unmanaged code: wchar_t* su = pu; // when "pu" goes out of scope, "su" becomes invalid! Ansi (8-bit) version: ScopedHGlobal s_handle(Marshal::StringToHGlobalAnsi(sm)); char* su = s_handle.c_str(); // when "s_handle" goes out of scope, "su" becomes invalid! Where ScopedHGlobal is a helper class written by myself: using namespace System::Runtime::InteropServices; public ref class ScopedHGlobal { public: ScopedHGlobal(IntPtr p) : ptr(p) { } ~ScopedHGlobal() { Marshal::FreeHGlobal(ptr); } char* c_str() { return reinterpret_cast(ptr.ToPointer()); } private: System::IntPtr ptr; }; 參考 http://www.pcreview.co.uk/forums/thread-2221676.php

0 意見: