Thread overview
double[][] to double**
Feb 10, 2013
Danny Arends
Feb 10, 2013
Ali Çehreli
Feb 10, 2013
Danny Arends
Feb 10, 2013
Ali Çehreli
February 10, 2013
I need to call some C code which takes a double**

In D I have a dynamic array X, Whats a good way of doing this ?

#SNIP

extern(C){
  void toCall(double** X, size_t d1, size_t d2);
}

void main(){
  double[][] X;

  // How to be able to:
  toCall(X, X.length, X[0].length);
}

#/SNIP

Danny Arends
http://www.dannyarends.nl
February 10, 2013
On 02/10/2013 11:38 AM, Danny Arends wrote:
> I need to call some C code which takes a double**
>
> In D I have a dynamic array X, Whats a good way of doing this ?
>
> #SNIP
>
> extern(C){
> void toCall(double** X, size_t d1, size_t d2);
> }
>
> void main(){
> double[][] X;
>
> // How to be able to:
> toCall(X, X.length, X[0].length);
> }
>
> #/SNIP
>
> Danny Arends
> http://www.dannyarends.nl

You need to use two properties of slices:

.ptr: Pointer to the first element
.length: The number of elements

import std.stdio;
import std.algorithm;
import std.range;

extern(C)
{
    void toCall(double** X, size_t d1, size_t d2)
    {
        for (size_t row = 0; row != d1; ++row) {
            for (size_t column = 0; column != d2; ++column) {
                writefln("%s,%s: %s", row, column, X[row][column]);
            }
        }
    }
}

void main(){
    double[][] X = [ [ 1, 2, 3 ], [ 10, 20, 30 ] ];

    double*[] X_c = X.map!(d => d.ptr).array;
    toCall(X_c.ptr, X_c.length, X[0].length);
}

The line with map is the equivalent of the following:

    double*[] X_c;
    foreach (slice; X) {
        X_c ~= slice.ptr;
    }

Ali

February 10, 2013
Thanks so much !

Why is this not easy 2 find :P
February 10, 2013
On 02/10/2013 12:05 PM, Danny Arends wrote:
> Thanks so much !
>
> Why is this not easy 2 find :P

We all know the feeling. :)

For future reference:

The spec:

  http://dlang.org/arrays.html#array-properties

TDPL:

  4.6 Arrays' Maverick Cousin: The Pointer

Programming in D:

  http://ddili.org/ders/d.en/pointers.html

  ("The .ptr property of arrays" section.)

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html