makerofthings7
makerofthings7

Reputation: 61473

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

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
}

Upvotes: 4

Views: 1399

Answers (1)

Sebastian Roether
Sebastian Roether

Reputation: 451

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.

Upvotes: 2

Related Questions