When you pass a managed
object into
unmanaged code using PInvoke, there is a chance that the garbage
collector will finalize the object before the unmanaged code is
finished with it. This can only happen when your managed code does
not reference the object after the PInvoke call. Because the garbage
collector's reach does not extend into unmanaged
code, this fools the garbage collector into thinking that you are
finished with it.
This class is used to wrap your managed object before passing it into
unmanaged code, and you are guaranteed that the garbage collector
will not touch it until the PInvoke call returns.
public struct HandleRef {
// Public Constructors
public HandleRef(object wrapper, IntPtr handle);
// Public Instance Properties
public IntPtr Handle{get; }
public object Wrapper{get; }
// Public Static Methods
public static explicit operator IntPtr(HandleRef value);
}