gcroot in c++/cli

gcroot is a C++/cli template class that eases holding managed types in C++/cli classes.

You can for example have the following:

#include <msclr/gcroot.h>
using namespace msclr;

class Native {
  public:
    Native(Object ^obj) :
      netstring(obj->ToString()) { // Initializing the gcroot<String ^>
    }
    ~Native() {
    }
    void Print() {
      array<Char> ^chars = netstring->GetChars(); // Dereferencing the gcroot<String ^>
      _wprintf("netstring is:");
      if (chars->Length > 0) {
        pin_ptr<Char> charptr = &(chars[0]);
        _wprintf("%s", (wchar_t const *)charptr);
      }
    }
  private:
    gcroot<String ^> netstring;
};

gcroot acts as a reference to the managed object or value type instance and is doing all the work when copying the object or value type instance. Normally you need to work with GCHandle and some C functions of the .NET framework. This is all encapsulated in gcroot.


When the .NET garbage collector runs, it determines which objects are still in use by doing reachability analysis. Only the managed heap is analyzed while looking for pointers to objects, so if you have a pointer from a native object to a managed object, you need to let the garbage collector know, so it can include it in reachability analysis, and so it can update the pointer if the target moves during compaction.

As rstevens said, the .NET GCHandle class does this, and C++/CLI is a C++-oriented wrapper for GCHandle which adds type safety and convenient syntax.

Tags:

C++ Cli