现在的位置: 首页 > 综合 > 正文

如何在MFC类中声明一个.Net FrameWork变量--gcroot(from msdn)

2013年10月02日 ⁄ 综合 ⁄ 共 1933字 ⁄ 字号 评论关闭

You cannot declare a handle type in a native type. vcclr.h provides the type-safe wrapper template gcroot, to refer to a CLR object from the C++ heap. This template lets you embed a virtual handle in a native type and treat it as if it were the underlying type.

The gcroot template is implemented using the facilities of the value class System::Runtime::InteropServices::GCHandle, which provides "handles" into the garbage-collected heap. Note that the handles themselves are not garbage collected and are freed when no longer in use by the destructor in the gcroot class (this destructor cannot be called manually). If you instantiate a gcroot object on the native heap, you must call delete on that resource.

The runtime will maintain an association between the handle and the CLR object, which it references. When the CLR object moves with the garbage-collected heap, the handle will return the new address of the object. A variable does not have to be pinned before it is assigned to a gcroot template.

Example

This sample shows how to create a gcroot object on the native stack.


  CopyCode imageCopy Code
// mcpp_gcroot.cpp
// compile with: /clr
#include <vcclr.h>
using namespace System;

class CppClass {
public:
   gcroot<String^> str;   // can use str as if it were String^
   CppClass() {}
};

int main() {
   CppClass c;
   c.str = gcnew String("hello");
   Console::WriteLine( c.str );   // no cast required
}

Output

 
hello

This sample shows how to create a gcroot object on the native heap.


  CopyCode imageCopy Code
// mcpp_gcroot_2.cpp
// compile with: /clr
// compile with: /clr
#include <vcclr.h>
using namespace System;

struct CppClass {
   gcroot<String ^> * str;
   CppClass() : str(new gcroot<String ^>) {}

   ~CppClass() { delete str; }

};

int main() {
   CppClass c;
   *c.str = gcnew String("hello");
   Console::WriteLine( *c.str );
}

Output

 
hello

This sample shows how to gcroot to hold references to value types (not reference types) in a native type by using gcroot on the boxed type.


  CopyCode imageCopy Code
// mcpp_gcroot_3.cpp
// compile with: /clr
#include < vcclr.h >
using namespace System;

public value struct V {
   String^ str;
};

class Native {
public:
   gcroot< V^ > v_handle;
};

int main() {
   Native native;
   V v;
   native.v_handle = v;
   native.v_handle->str = "Hello";
   Console::WriteLine("String in V: {0}", native.v_handle->str);
}

Output

 
String in V: Hello

抱歉!评论已关闭.