c++(/clr)非託管類型和託管類型互轉
轉載於: http://www.cnblogs.com/kekec/archive/2011/03/25.html
以下代碼必須有「Common Language Runtime Support(/clr)」 和「MFC」支持
轉載於: 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 System::Runtime::InteropServices;
14 _variant_t* vt = new _variant_t();
15 System::IntPtr^ pvar = (gcnew System::IntPtr((void*)vt));
16 Marshal::GetNativeVariantForObject(obj,*pvar);
17 return vt;
18 }
更多:請參考.net庫 System.Runtime.InteropServices 命名空間下的類,特別是 Marshal 類。
留言
張貼留言