Array of arrays (float**)

Announcements and discussion for PInvoke

Array of arrays (float**)

Postby yoavhacohen » Thu Dec 25, 2008 12:03 pm


I have a native function that gets an array of pointers to arrays:

Code: Select all
extern __declspect(dllexport) void foo(float**);

And I have a 2D managed array which I want to give the function as a parameter, *WITHOUT* copy its data.

I wrote this code, but sometimes I get an AccessViolationException when I call to the function (in other cases it works fine):

Code: Select all
internal static extern void foo(IntPtr ptr);

public void FooWrapper(float[,] array)
   int dim = array.GetLength(1);
   int nRows = array.GetLength(0);

   GCHandle _pinnedArray = GCHandle.Alloc(array, GCHandleType.Pinned);
      fixed (float* fixedFirstRow = &array[0,0])
           float* rowPtr = (float*)(new IntPtr(fixedFirstRow).ToPointer());
           // Allocate an array of float* pointers
           int[] pointersToRows = new int[nRows];
           for (int row = 0; row < nRows; ++row, rowPtr += dim)
                pointersToRows[row] = new IntPtr(rowPtr).ToInt32;
           GCHangle _rowPtrPinned = GCHandle.Alloc(pointersToRows, GCHanfleType.Pinned);
           fixed (int* pointersToRowsHandle = &pointersToRows[0])
               FooWrapper(new IntPtr(pointersToRowsHandle));

What am I doing wrong?
Is there a better way to do this?

Thanks in advance,
Posts: 2
Joined: Sat Dec 20, 2008 10:57 pm
Location: Israel

Return to PInvoke.Net

Who is online

Users browsing this forum: No registered users and 0 guests