Does GCHandle.Alloc do anything beyond keeping a reference to an object?

admin

Administrator
Staff member
<a href="http://msdn.microsoft.com/en-US/library/a95009h1(v=vs.110).aspx" rel="nofollow">
Code:
GCHandle.Alloc
</a> "protects the object from garbage collection," but merely holding a reference to that object in a static variable will also prevent it from being collected. What benefit does
Code:
GCHandle.Alloc
provide (assuming
Code:
GCHandleType.Normal
)?

<a href="https://limbioliong.wordpress.com/2011/06/19/delegates-as-callbacks-part-2/" rel="nofollow">This article</a> says that delegates "need not be fixed at any specific memory location" but I can't find any documentation on MSDN to back that statement up. If the delegate is moved by the CLR garbage collector, how can the umanaged library find it so that it can be called?

Note that delegates <em>cannot</em> be pinned; you will get an exception stating "Object contains non-primitive or non-blittable data".