如何:使用本机类型声明句柄

更新:2007 年 11 月

不能在本机类型中声明句柄。vcclr.h 提供类型安全的包装模板 gcroot,以引用 C++ 堆中的 CLR 对象。此模板使您可以在本机类型中嵌入虚句柄,并且将其视为基础类型。

该 gcroot 模板是使用值类 System::Runtime::InteropServices::GCHandle 的功能实现的,它将“句柄”提供到垃圾回收堆中。请注意,句柄本身不是垃圾回收的,并且不再使用时会被 gcroot 类中的析构函数(无法手动调用此析构函数)释放。如果实例化本机堆上的 gcroot 对象,必须调用该资源上的删除。

运行时将维护句柄与 CLR 对象之间的关联,它将引用该关联。当 CLR 对象与垃圾回收堆一起移动时,该句柄将返回该对象的新地址。变量分配给 gcroot 模板前不必被固定。

示例

此示例说明如何在本机堆栈上创建 gcroot 对象。

// 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
}

hello

此示例说明如何在本机堆上创建 gcroot 对象。

// 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 );
}

hello

此示例说明如何用 gcroot 实现通过使用装箱类型上的 gcroot 对本机类型中的值类型(不是引用类型)的引用。

// 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);
}

String in V: Hello

请参见

参考

使用 C++ Interop(隐式 PInvoke)