Is GCHandleType.Pinned similar to using “fixed” keyword?

半世苍凉 提交于 2019-12-07 10:53:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!