Pinvoking a native function with array arguments

后端 未结 2 1166
无人及你
无人及你 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: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

提交回复
热议问题