[Numpy-discussion] Pass 2d ndarray into C **double using ctypes

Sturla Molden sturla.molden at gmail.com
Thu Jan 1 14:35:28 EST 2015


On 01/01/15 20:25, Yuxiang Wang wrote:

> #include <stdlib.h>
>
> __declspec(dllexport) void foobar(const int m, const int n, const
> double **x, double **y)
> {
>      size_t i, j;
>      y = (** double)malloc(sizeof(double *) * m);
>      for(i=0; i<m; i++)
>          y[i] = (*double)calloc(sizeof(double), n);
>      for(i=0; i<m; i++)
>          for(j=0; j<n; j++)
>              y[i][j] = x[i][j];
> }

> Was I doing something wrong here?

You are not getting the data back because of the malloc/calloc 
statements. The numpy array y after calling _foobar is still pointing to 
its original buffer, not the new memory you allocated. You just created 
a memory leak. Try this instead:

__declspec(dllexport) void foobar(const int m, const int n, const
double **x, double **y)
{
     size_t i, j;
     for(i=0; i<m; i++)
         for(j=0; j<n; j++)
             y[i][j] = x[i][j];
}


Sturla








More information about the NumPy-Discussion mailing list