以下代码必须有“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 类。