问题
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:
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.
来源:https://stackoverflow.com/questions/21066441/is-gchandletype-pinned-similar-to-using-fixed-keyword