This documentation is archived and is not being maintained.

16.3 __gc Pointers in Unmanaged Classes

Visual Studio .NET 2003

It is not valid to declare a member of an unmanaged class to have __gc pointer type. In order to "point" to a managed object from the C++ heap, the header file vcclr.h provides the type-safe wrapper template gcroot. Use of this template allows the programmer to embed a virtual __gc pointer in an unmanaged class and treat it as if it were the underlying type.


// mcpp_nested_classes7.cpp
// compile with: /clr
#using <mscorlib.dll>
#include <vcclr.h>
using namespace System;

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

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



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; they must be manually freed when no longer in use (performed by the destructor in the gcroot class). The memory management for any unmanaged class containing a gcroot member must be robust to avoid leaking GCHandle slots.

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