Passing multidimensional D arrays to C (sorry if duplicate)

bearophile bearophileHUGS at
Thu Oct 14 09:54:58 PDT 2010

Andrej Mitrovic:

> But I haven't figured out an elegant way of passing multidimensional arrays to functions expecting pointers to pointers.

In D there are no nD dynamic arrays.
nD arrays in D may be fixed-sized. The fixed-sized ones are just a contiguous sequence of values (so their rows may be not aligned to 16 bytes).
The dynamic arrays may contain other dynamic arrays, so a 2D dynamic array is a 2-word struct that points to an array of 2-word structs, each of them points to an array of the items (so if the row lengths are all the same you are wasting memory).
There are few different ways to allocate 2D arrays in C, if your C function expects a pointer to pointers, then it wants an array of pointers to the row, so the D structure is not fit, you need to build an array of pointers:

void main() {
    enum int side = 10;
    alias int T;
    auto m = new T[][](side, side);
    auto m2 = new T*[side];
    foreach (i, ref p; m2)
        p = m[i].ptr;
    // now you may read m2.ptr from C


More information about the Digitalmars-d-learn mailing list