double[][] to double**

Ali Çehreli acehreli at yahoo.com
Sun Feb 10 11:58:46 PST 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



More information about the Digitalmars-d-learn mailing list