gcroot in c++/cli

时光毁灭记忆、已成空白 提交于 2019-12-10 12:33:33

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5005247/gcroot-in-c-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!