I am completely confused with how to go about calling functions in native dll with array arguments.
Example:
The function is defined in the C# project as:
Your C++ code is broken. The caller allocates the array, and the callee populates it. Like this:
extern "C" _declspec(dllexport) void modifyArray(int* x, int len)
{
for (int i=0; i<len; i++)
x[i] = i;
}
As far as your p/invoke call goes, SetLastError
should not be true
. The function is not calling SetLastError
. It should be:
[DllImport("Project2.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void modifyArray(int[] x, int len);
This has nothing to do with PInvoke, this is just a plain old C issue. You would have the exact same problem if you called modifyArray
from C
int* pArray = NULL;
modifyArray(pArray, len);
pArray == NULL; // true!
In modifyArray
you are trying to change where x
points to. This change won't be visible to the calling function because the pointer is passed by value. In order to change where it points to you need to pass a double pointer
void modifyArray(int** x, int len) {
*x = ...;
}
Note that you are currently trying to return stack allocated memory instead of heap allocated memory. That is incorrect and will lead to problems down the line