C++(/clr)托管类型与非托管类型互相转换

 
 
2011-07-25 17:15

1. 字符窜之间的转换

1// 托管类型到非托管类型
2 inline cstring managetounmanagestr(system::string^ cmstr)
3{
4using namespace system::runtime::interopservices;
5 cstring cstr = (char*)(marshal::stringtohglobalansi(cmstr)).topointer();
6return cstr;
7}
8
9 // 非托管类型到托管类型
10 inline system::string^ unmanagetomanagestr(const cstring& cstr)
11{
12const char* cc = (lpctstr)cstr;
13 system::string^ cmstr = gcnew system::string(cc);
14return 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 }

你可能感兴趣的:(C++(/clr)托管类型与非托管类型互相转换)