PInvoke, pointers and array

We are creating an application in C #,. Net 4.0 on Win7 x64, focusing on x32.

We use a third-party library in our application. We understand that this library is written using C ++. However, for C # developers to use this library, they wrapped it with P / Invoke, so that we call the API functions.

One of the API calls is as follows:

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

This function reads numBytes of data from an external device and places it in the data []. As you can see, it expects to see a C # byte array as the third argument. Now, our problem is that we would like to read data at any place in a predefined array. For instance:

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

If we used C / C ++, that would be trivial. Given that the base API is written in C ++, I feel that we must do this in C # as well, but I cannot figure out how to do this in C #. Maybe we can somehow call the base library not through the supplied P / Invoke interface and write our own interface?

Any ideas would be appreciated.

Hi,

+5
source share
5 answers

While the other answers are close here, none of them are complete.

First you just need to declare your own p / invoke declaration. This is a nice thing about p / invoke; There has never been only one way to do this.

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

Now you can call him using

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

, .

Byte[] myData = new Byte[1024*1024*16];
fixed( Byte * pB = &myData[350])
{
   ReadFromDevice(0x100, 20000,pB  ) 
} 

.

ReadFromDevice(int deviceAddress, int numBytes, Byte * data);
+3

#.

, dll ( ++), IntPtr , 350 Add ( intptr)

- : http://msdn.microsoft.com/en-us/library/system.intptr.add.aspx#Y811

+2

:

ReadFromDevice(int deviceAddress, int numBytes, ref byte data);

...


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

.

, - DllImport -, .

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

. , , .

, , , , .

, , , , specfic- (, -, ), , ++ , .

0

All Articles