Pinvoking a native function with array arguments

后端 未结 2 1149
无人及你
无人及你 2021-01-16 06:53

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:

相关标签:
2条回答
  • 2021-01-16 07:30

    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);
    
    0 讨论(0)
  • 2021-01-16 07:34

    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

    0 讨论(0)
提交回复
热议问题