c++(/clr)非託管類型和託管類型互轉 轉載於: http://www.cnblogs.com/kekec/archive/2011/03/25.html 以下代碼必須有「Common Language Runtime Support(/clr)」 和「MFC」支持 1. 字符竄之間的轉換 1 // 託管類型到非託管類型 2 inline CString ManageToUnManageStr(System::String^ cmStr) 3 { 4 using namespace System::Runtime::InteropServices; 5 CString cStr = (char*)(Marshal::StringToHGlobalAnsi(cmStr)).ToPointer(); 6 return cStr; 7 } 8 9 // 非託管類型到託管類型 10 inline System::String^ UnManageToManageStr(const CString& cStr) 11 { 12 const char* cc = (LPCTSTR)cStr; 13 System::String^ cmStr = gcnew System::String(cc); 14 return cmStr; 15 } 2. 對象之間的轉換 1 // _variant_t到Object對象 2 inline System::Object^ VarToObject(_variant_t var) 3 { 4 using namespace System::Runtime::InteropServices; 5 System::IntPtr^ pvar = gcnew System::IntPtr(&var); 6 System::Object^ obj = Marshal::GetObjectForNativeVariant(*pvar); 7 return obj; 8 } 9 10 // Object對象到_variant_t 11 inline _variant_t* ObjectToVar(System::Object^ obj) 12 { 13 using namespace