被GCHandleType.Pinned类似于使用"固定"关键词? [英] Is GCHandleType.Pinned similar to using "fixed" keyword?

查看:1168
本文介绍了被GCHandleType.Pinned类似于使用"固定"关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的IntPtr试验中的安全的代码,比较它的东西是如何在不安全的方式完成的。



时GCHandleType.Pinned相似?在不安全模式下使用固定

 的GCHandle pinnedArray = GCHandle.Alloc(字节数组,GCHandleType.Pinned); 
的IntPtr指针= pinnedArray.AddrOfPinnedObject();
//做你的东西
pinnedArray.Free();



VS

 字节[]缓冲区=新的字节[255]; 
固定(字节* P =缓冲)
{
IntPtr的PTR =(IntPtr的)P;
//你的东西在这里
}


解决方案

是的,结果是一样的。所不同的是在使用情况:假设异步填充的缓冲器的外部的方法,一旦它完成比调用回调。你不能传递一个使用固定的关键字,因为一旦你的变量超出范围,它是未固定,而外部方法仍尝试使用固定的缓冲区指针。


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
}

解决方案

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.

这篇关于被GCHandleType.Pinned类似于使用"固定"关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆