Is GCHandleType.Pinned similar to using "fixed" keyword?

1.3k Views Asked by At

I'm experimenting with IntPtr in "safe" code, comparing it to how things are done in the "unsafe" mode.

Is GCHandleType.Pinned similar to using "fixed" in unsafe mode?

GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
//do your stuff
pinnedArray.Free();

vs

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}
1

There are 1 best solutions below

0
On

Yes, the result is the same. The difference is in the usage: Assume an external method that asynchronously fills your buffer and than invokes a callback once it is finished. You cannot pass a buffer pointer that is pinned using the fixed keyword, because once your variable goes out of scope, it is unpinned while the external method still tries to use it.