I’ve been trying to transfer a Julia matrix of Float64 to a C function that has a “double **arg” but it does not work as intended so help would be appreciated.

C function I want to call (simplified body just to get idea across):

```
double emd2(int n_x, double *weight_x, int n_y, double *weight_y, double **cost) {
double sum = 0.0;
int i, j;
for(i = 0; i < n_x; i++) {
sum = sum + weight_x[i];
}
for(i = 0; i < n_y; i++) {
sum = sum + weight_y[i];
}
for(j = 0; j < n_y; j++) {
for(i = 0; i < n_x; i++) {
sum = sum + cost[j][i];
}
}
return sum;
}
```

then I compile this into a lib called libemd and define a low-level function to call it like so:

```
libemd_emd2(n_x, weight_x, n_y, weight_y, cost) =
ccall((:emd2,libemd), Cdouble,
(Cint, Ptr{Cdouble}, Cint, Ptr{Cdouble}, Ptr{Ptr{Cdouble}}),
n_x, pointer(weight_x), n_y, pointer(weight_y), pointer(cost))
```

but when I then try to use it:

```
w1 = [0.4, 0.2, 0.2, 0.1, 0.1]
w2 = [0.6, 0.2, 0.2]
cost = ones(Float64, 5, 3)
cost_ref = [Ref(cost,i) for i=1:size(cost,1):length(cost)]
libemd_emd2(length(w1), w1, length(w2), w2, cost_ref)
```

The result is some large number rather than the sums of the values of the matrix and the two arrays. Seems it is reading some random place in memory so I guess I set up the pointers the wrong way or something. I based my solution on this stackoverflow entry: Calling a C function from Julia and passing a 2D array as a pointer of pointers as argument - Stack Overflow

What am I missing here? Thanks for any advice.