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?
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.
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.
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'.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With