如何固定一个字节数组? [英] How can I pin an array of byte?

查看:102
本文介绍了如何固定一个字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想固定一个10兆字节长的字节数组,以便托管和非托管代码都能在其上工作。

I want to pin an array of bytes which is 10 megabytes long so that managed and unmanaged code can work on it.

我的情况是我有一个非托管的驱动程序从设备读取一些数据并将其写入大数组,托管应用程序则读取该数据。

My scenario is that I have an unmanaged driver which reads some data from the device and writes it to the big array and the managed application just reads that data.

类似这样的事情:

byte[] dataArray = new byte[10*1024*1024];

我想固定dataArray以便GC不会移动它。

I want to pin dataArray so that GC does not move it.

当我刚运行该应用程序时,我得到一个DataAbortApplication,然后在互联网上阅读后发现我应该固定 dataArray 为避免此错误。

What happens actually when I just run the application, I get a DataAbortApplication, and after reading on the internet I found out that I should pin the dataArray to avoid this error.

我应该怎么做?

推荐答案

有两种方法可以做到这一点。第一种是使用 fixed 语句:

There are 2 ways to do this. The first is to use the fixed statement:

unsafe void UsingFixed()
{
    var dataArray = new byte[10*1024*1024];
    fixed (byte* array = dataArray)
    {
        // array is pinned until the end of the 'fixed' block
    }
}

但是,听起来好像您希望将阵列固定更长的时间。您可以使用 GCHandle 来完成此任务:

However, it sounds like you want the array pinned for a longer period of time. You can use GCHandles to accomplish this:

void UsingGCHandles()
{
    var dataArray = new byte[10*1024*1024];
    var handle = GCHandle.Alloc(dataArray, GCHandleType.Pinned);

    // retrieve a raw pointer to pass to the native code:
    IntPtr ptr = handle.ToIntPtr();

    // later, possibly in some other method:
    handle.Free();
}

这篇关于如何固定一个字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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