Search code examples
c++-cli

gcroot in c++/cli


What does gcroot mean? I found it in code I am reading.


Solution

  • 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.