Fixed gear operator

I have a jagged array that I need to pass to an 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 not used and is removed due to compilation. Then the fixed application in accordance with it is also deleted. Thus, the array is moved by the GC so that the ptrArray elements become invalid.

What is the best way to transmit jagged arrays as one-dimensional arrays of pointers to your own methods?

Update:

Here is the C ++ code for NativeMethod:

NativeClass::NativeMethod(const int* array)
+3
source share
2 answers

, , , , . , GC :

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

UPDATE

, .

+3

# ++ Pinvoke, #, . GC , . ( ):

[Test, Ignore]
public void Test_JaggedArrayPInvoke()
{
    var jaggedArray = new int[3][];
    jaggedArray[0] = new int[1] { 9 };
    jaggedArray[1] = new int[4] { 1, 2, 3, 8 };
    jaggedArray[2] = new int[2] { 1, 2 };

    //GCHandle mainHandle = GCHandle.Alloc(jaggedArray, GCHandleType.Pinned);   //This does not work

    var pinnedHandles = new GCHandle[3];                    
    var jaggedArrayPtrs = new IntPtr[3];
    for (int i = 0; i < 3; i++)
    {
        pinnedHandles[i] = GCHandle.Alloc(jaggedArray[i], GCHandleType.Pinned);
        jaggedArrayPtrs[i] = pinnedHandles[i].AddrOfPinnedObject();
    }

    var result = JaggedArrayPInvoke_TEST(jaggedArrayPtrs);

    Console.WriteLine(result);  //returns 8 as it should.

    //mainHandle.Free();
    for (int i = 0; i < 3; i++)
    {
        pinnedHandles[i].Free();
    }
}

//The C++ test method:

extern "C" __declspec(dllexport) int __stdcall JaggedArrayPInvoke_TEST(int** jaggedArray);
__declspec(dllexport) int __stdcall JaggedArrayPInvoke_TEST(int** jaggedArray) 
{ 
   return jaggedArray[1][3];
}

mainHandle, . " ". , jaggedArray ? ( , GC , .) , jaggedArray GC.

0

Source: https://habr.com/ru/post/1771710/


All Articles