c# - Does GCHandle.Alloc do anything beyond keeping a reference to an object? -
gchandle.alloc
"protects object garbage collection," merely holding reference object in static variable prevent being collected. benefit gchandle.alloc
provide (assuming gchandletype.normal
)?
this article says delegates "need not fixed @ specific memory location" can't find documentation on msdn statement up. if delegate moved clr garbage collector, how can umanaged library find can called?
note delegates cannot pinned; exception stating "object contains non-primitive or non-blittable data".
managed objects discovered garbage collector walking appdomain statics , stacks of running threads , objects reference on gc heap. there scenarios collector not capable of finding reference object that's live , should not collected.
this happens when unmanaged code uses such objects. code not jitted gc has no way discover object references back, stack frame of such code cannot reliably inspected find pointer back. must ensure gc still sees reference. gchandle does. uses dedicated table of gc handles built inside clr. allocate entry table gchandle.alloc() , release again later gchandle.free(). garbage collector adds entries in table graph of objects discovered when performs collection.
the gcroot<> keyword in c++/cli example of this. allows writing unmanaged code can store simple raw pointer , have converted managed object reference needed. gchandle.tointptr() method generates pointer, fromintptr() recovers object reference. gchandle table entry ensures object won't collected until unmanaged code explicitly calls free(). done c++ destructor.
gchandle supports ability pin object, used when need marshal native code , pinvoke marshaller can't job done. you'd pass return value of gchandle.addrofpinnedobject(). , implements weak references, although you'd use weakreference class that. , implements async pinned handles, allowing pinned i/o buffers unpinned automatically on i/o completion, capability that's not directly exposed. yes, gchandle more keeping reference.
and significant question delegates, clr supports using delegate call native code. underlying helper function marshal.getfunctionpointerfordelegate(). dynamically builds machine code stub allows native code callback managed code. requires delegate object stay referenced, gchandle.alloc() used that. isn't way, storing delegate static variable way ensure delegate object won't garbage collected. delegate doesn't otherwise have pinned, gchandletype.normal fine.
this used lot in .net program, of out of sight. particularly in .net framework code , in pinvoke marshaller. having use gchandle protect delegate object necessary when native code stores function pointer , can make callbacks later.
Comments
Post a Comment