PInvoke的,指针和数组复制 [英] PInvoke, pointers and array copy

查看:167
本文介绍了PInvoke的,指针和数组复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在建立一个应用程序在C#.NET 4.0,对Win7的X64,X32定位

We're building an application on c#, .net 4.0, on Win7 x64, targeting x32.

我们在我们的应用程序中使用第三方库。据我们了解,该库是用C ++写的。然而,为了让C#开发人员使用这个库,他们已经把它包使用P / Invoke,所以这就是我们如何调用API函数。

We are using a 3rd party library in our application. We understand that this library is written using C++. However, to let c# developers use this library, they've wrapped it using P/Invoke, so that's how we call the API functions.

其中一个API调用如下:

One of the API calls is as follows:

ReadFromDevice(int deviceAddress, int numBytes, Byte[] data);

此功能从外部设备读取数据的numBytes和数据[]放置它。正如你所看到的,希望看到一个C#Byte数组作为第三个参数。现在,我们的问题是,我们想读取数据以predeclared阵列的任意位置。例如:

This function reads numBytes of data from an external device and places it in data[]. As you can see, it expects to see a C# Byte array as the 3rd argument. Now, our problem is, we would like to read data to an arbitrary location in a predeclared array. For example:

Byte[] myData = new Byte[1024*1024*16];
ReadFromDevice(0x100, 20000, &myData[350]) // Obviously not possible in C#

如果我们使用C / C ++,这将是微不足道的。鉴于底层API是用C ++,我觉得我们应该能够做到这一点在C#中为好,不过,我无法弄清楚如何做到这一点在C#。也许我们能以某种方式调用基础库不通过提供的P / Invoke接口,并编写自定义的界面?

If we were using C/C++, this would be trivial. Given that the underlying API is written in C++, I feel that we should be able to do this in c# as well, however, I can't figure out how to do this in c#. Maybe we can somehow call the underlying library not through the supplied P/Invoke interface and write a custom interface?

任何想法,将AP preciated。

Any ideas would be appreciated.

问候,

推荐答案

在这里其他的答案比较接近,没有一个是比较齐全的。

While the other answers here are close, none are quite complete.

首先,你只需要简单地声明自己的P / Invoke声明。这是关于P中的甜蜜的事/调用;从未有只有一个办法做到这一点。

First you simply need to declare your own p/invoke declaration. This is the sweet thing about p/invoke; There's never just one way to do it.

[DllImport("whatever.dll")]
unsafe extern static void ReadFromDevice(int deviceAddress, int numBytes, byte* data);

现在你可以把它叫做

unsafe static void ReadFromDevice(int deviceAddress, byte[] data, int offset, int numBytes)
{
    fixed (byte* p = data)
    {
        ReadFromDevice(deviceAddress, numBytes, p + offset);
    }
}

这篇关于PInvoke的,指针和数组复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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