Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a pointer to an array using p/invoke in C#?

Tags:

Example C API signature:

void Func(unsigned char* bytes);

In C, when I want to pass a pointer to an array, I can do:

unsigned char* bytes = new unsigned char[1000]; Func(bytes); // call 

How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?

like image 643
Randy Sugianto 'Yuku' Avatar asked Nov 14 '08 02:11

Randy Sugianto 'Yuku'


People also ask

Can we pass a pointer to an array to a function?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

Can you pass an array as a pointer in C?

Array can be passed to function in C using pointers and because they are passed by reference changes made on an array will also be reflected on the original array outside function scope.

How do you declare a pointer to an array?

p = arr; // Points to the whole array arr. p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole array arr. The base type of p is int while base type of ptr is 'an array of 5 integers'.

Can we use pointer in array?

Pointers are variables which stores the address of another variable. When we allocate memory to a variable, pointer points to the address of the variable. Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory.


1 Answers

The easiest way to pass an array of bytes is to declare the parameter in your import statement as a byte array.

[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true] public extern static void Func(byte[]);  byte[] ar = new byte[1000]; Func(ar); 

You should also be able to declare the parameter as an IntPtr and Marshal the data manually.

[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true] public extern static void Func(IntPtr p);  byte[] ar = new byte[1000]; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * ar.Length); Marshal.Copy(ar, 0, p, ar.Length); Func(p); Marshal.FreeHGlobal(p); 
like image 156
asponge Avatar answered Nov 09 '22 03:11

asponge