Understanding gcroot

*爱你&永不变心* 提交于 2019-12-03 04:31:19

Garbage collection doesn't just remove unreferenced objects, it also moves around objects that are still referenced, e.g. to defragment the free memory pool. When the article talks about objects moving in the CLR heap, it's probably saying "when garbage collection moves a still-referenced object, the gcroot handle will be automatically updated to still point to the CLR object."

You can prevent GC from moving objects around by using the pin_ptr keyword, like so:

Object ^obj = gcnew <something>;
pin_ptr pinned = obj;  /* obj won't move due to GC as long as pinned is in scope. */
/* do something interop-y here, pass to native code in a DLL, etc. */

See this article for more information about pinning.

Observation: The article may have a typo. If it had said "within the garbage-collected heap" instead of "with the garbage-collected heap", would that have improved your understanding? The way it's phrased in the article makes it sound like the very earth would move under your feet whenever GC cleaned house.

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