Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 789
Robert Venables Avatar asked Feb 15 '26 22:02

Robert Venables


2 Answers

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?

like image 103
dtb Avatar answered Feb 18 '26 12:02

dtb


This doesn't work because it's not possible to box a pointer in .NET, so you can never call the Array.SetValue and pass an int*.

Can you declare MyMethod to accept int*[,,,] instead?

Edit: for further reading, an interesting recent post from Eric Lippert.

like image 35
Tim Robinson Avatar answered Feb 18 '26 10:02

Tim Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!