Wednesday, September 2, 2009


I seem to struggle to find this little class whenever I need to, and usually only find it after exhausting all the methods on Marshal before eventually finding it using Google.

GCHandle is used to get the address (IntPtr) for an object and can pin the object so it won't be moved while native code is using it.

This blog describes why GCHandle doesn't implement IDisposable.

Trap for young players: if your object is a struct or other value type, it will be boxed and that copy will be pinned, not your original structure. This boxing happens when you pass your instance to the GCHandle constructor and it is cast to the object base class.


Post a Comment