views:

938

answers:

2

Simple question here: is there any way to convert from a jagged array to a double pointer?

e.g. Convert a double[][] to double**

This can't be done just by casting unfortunately (as it can in plain old C), unfortunately. Using a fixed statement doesn't seem to resolve the problem either. Is there any (preferably as efficient as possible) way to accomplish this in C#? I suspect the solution may not be very obvious at all, though I'm hoping for a straightforward one nonetheless.

+1  A: 

A double[][] is an array of double[], not of double* , so to get a double** , we first need a double*[]

double[][] array = //whatever
//initialize as necessary

fixed (double* junk = &array[0][0]){

    double*[] arrayofptr = new double*[array.Length];
    for (int i = 0; i < array.Length; i++)
        fixed (double* ptr = &array[i][0])
        {
            arrayofptr[i] = ptr;
        }

    fixed (double** ptrptr = &arrayofptr[0])
    {
        //whatever
    }
}

I can't help but wonder what this is for and if there is a better solution than requiring a double-pointer.

pyrochild
Unfortunately I can't avoid the user of a double pointer, since I'm calling an external C function, and C# can't automatically marshall jagged arrays.
Noldorin
I'll give this a go as soon as possible by the way. Thanks.
Noldorin
I had to edit this like 6 times to get around SO wanting to parse the *s as italics. The preview window and the actual post were inconsistent in their interpretation...
pyrochild
@zachrrs: So your method seems to do the job well enough. Looping through one of the dimensions isn't the ideal solution in my mind, though I'm thinking it might be necessary in C#. I'm going to leave this question open for a bit longer in case anyone else has something new to add. If not, the answer will be yours. :)
Noldorin
A: 

I've gone with zachrrs solution for the time being (which was what I was suspecting might need to be done in the first place). Here it is an extension method:

public static double** ToPointer(this double[][] array)
{
    fixed (double* arrayPtr = array[0])
    {
        double*[] ptrArray = new double*[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            fixed (double* ptr = array[i])
                ptrArray[i] = ptr;
        }

        fixed (double** ptr = ptrArray)
            return ptr;
    }
}
Noldorin