Understanding gcroot
I have been reading this article to understand the gcroot template. I understand the
gcroot provides handle开发者_运维知识库s into the garbage collected heap
and that
the handles themselves are not garbage collected.
What I don't understand is the following:
When the CLR object moves with the garbage-collected heap, the handle will return the new address of the object. A variable does not have to be pinned before it is assigned to a gcroot template.
Does that mean that the CLR object will be deleted by the garbage collector even if there is a gcroot handle referencing that object?
What is the "new address" that it refers to? And what does it mean that the "variable does not have to be pinned before it is assigned to a gcroot template"?
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.
精彩评论