Search code examples
c#multidimensional-arrayunsafe-pointers

Dynamically setting value on array of pointers to integers


I have a multidimentional array of pointers to integer (of unknown rank) being passed into my function as such:

    public unsafe static void MyMethod(Array source, ...)
    {
         //...
    }

Multidimensional arrays of pointers are being constructed outside of the method and being passed in. Here's an example:

int*[,,,] testArray = new int*[10,10,5,5];

MyMethod(testArray);

How can I set a value at an runtime-computed index in the array? Array.SetValue(...) works perfectly fine for non-pointer arrays, but refuses to work for my int* array. Using reflector, I see SetValue reduces down to calling InternalSetValue which takes an object for the value but it's marked as extern and I can't see the implementation. I took a shot in the dark and tried passing in boxed pointer, but no luck.


Solution

  • This works:

    unsafe static void MyMethod(int** array)
    {
        array[10] = (int*)0xdeadbeef;
    }
    
    private static unsafe void Main()
    {
        int*[, , ,] array = new int*[10, 10, 10, 10];
    
        fixed (int** ptr = array)
        {
            MyMethod(ptr);
        }
    
        int* x = array[0, 0, 1, 0]; // == 0xdeadbeef
    }
    

    Does that help?


    Question to the experts: Is it wrong to assume that the array is allocated consecutively in memory?