Search code examples
c#pointerspinvokefixedjagged-arrays

Fixed statement with jagged array


I have jagged array which I need to pass to external method.

[DllImport(...)]
private static extern int NativeMethod(IntPtr[] ptrArray);

...

fixed (ulong* ptr = array[0])
{
    for (int i = 0; i < array.Length; i++)
    {
        fixed (ulong* p = &array[i][0])
        {
            ptrArray[i] = new IntPtr(p);
        }
    }

    NativeMethod(ptrArray);
}

The problem is that ptr is unused and is removed due compilation. Than fixed statement according to it is removed too. So array be moved by GC in that way that ptrArray elements become invalid.

What is the best way for passing jagged arrays as single-dimensional arrays of pointers to native methods?

Update:

Here is the C++ code for NativeMethod:

NativeClass::NativeMethod(const int* array)

Solution

  • Your problem is with the fact that you need array to be fixed since that is the one you are using. You can pin the array so that GC does not collect it:

     GCHandle h = GCHandle.Alloc(array, GCHandleType.Pinned);
    

    UPDATE

    As you have correctly pointed out, each array inside the array needs pinning as well.