views:

43

answers:

2

Hi all!

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)
+2  A: 

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.

Aliostad
But it still can move it.
levanovd
You are right, I was looking for Pinned but could not find it.
Aliostad
Now you just need to pass the h.AddrOfPinnedObject() to the native method.
A_Nablsi
Thank you! Your idea is very helpful. The only thing I wand to add is that your code will produce exception, because array is array of arrays but not of basic types. You should pin (and then .Free()!) every array[i] but not array itself.
levanovd
You are right, I will add this note for the sake of completeness
Aliostad