Pinned Object
suggest changeGC (Garbage Collector) is responsible for cleaning our garbage.
While the GC cleans our garbage, it removes the unused objects from the managed heap, which causes heap fragmentation. When the GC is done with the removal, it performs a heap compression (defragmentation) which involves moving objects on the heap.
Since the GC isn’t deterministic, when passing a managed object reference to native code, the GC can run at any time. If it runs just after an interop call, the object whose reference was passed to native code may move on the managed heap. The native side then holds an invalid address.
In this scenario, you should pin the object before passing it to native code.
Pinned Object
Pinned object is an object that is not allowed to move by GC.
Gc Pinned Handle
You can pin an object with GCHandle.Alloc:
GCHandle handle = GCHandle.Alloc(yourObject, GCHandleType.Pinned);
- Obtaining a pinned GCHandle to managed object marks a specific object as one that cannot be moved by GC, until freeing the handle
Example:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void EnterCriticalSection(IntPtr ptr);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void LeaveCriticalSection(IntPtr ptr);
public void EnterCriticalSection(CRITICAL_SECTION section)
{
GCHandle handle = default(GCHandle);
try
{
handle = GCHandle.Alloc(section, GCHandleType.Pinned);
EnterCriticalSection(handle.AddrOfPinnedObject());
//Do Some Critical Work
LeaveCriticalSection(handle.AddrOfPinnedObject());
}
finally
{
if (handle.IsAllocated)
handle.Free();
}
}
Precautions
- When pinning an object, especially a large one, release the pinned
GCHandleas soon as possible, since it interrupts heap defragmentation. - If you forget to free the
GCHandle, nothing else will. Free it in afinally.CRITICAL_SECTIONin the sample is only a stand-in for the native structure.