I try to convert a C double* in numpy array on Cython but I didn't succeed yet. I found these usefull links: Force NumPy ndarray to take ownership of its memory in Cython https://github.com/numpy/numpy/issues/8253
But everytime I use the following .pyx file with Cython it makes Jupyter crash (dead kernel):
.c file:
#include<stdlib.h>
#include "test.h"
double* test1(int n) {
double* A=(double*)calloc(n,sizeof(double));
int i;
for (i=0;i<n;i++) {
A[i]=i+0.5; }
return(A); }
I also try with malloc with the same result.
.pyx file:
cimport c_test
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.float64_t DTYPE_t
cdef extern from "numpy/arrayobject.h":
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
cdef data_to_numpy_array_with_spec(void * ptr, np.npy_intp N, int t):
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, t, ptr)
PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)
return arr
def test(n):
cdef double* t1
t=data_to_numpy_array_with_spec(c_test.test1(n),n,np.NPY_FLOAT64)
return(t)
The c_fct.test1 function return a C double* of n double that I want to convert into a numpy array which own the data to avoid memory leak. Without the line PyArray_ENABLEFLAGS(t, np.NPY_ARRAY_OWNDATA)
everything works fine but the memory is not deallocated when the numpy array is destroyed.
jupyter notebook:
import cy_test as ct
ct.test(1000)
c_test.pxd file:
cdef extern from "test.h":
double* test1(int n)
My setup.py file looks like this:
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import numpy as np
ext_modules = cythonize([Extension("cy_test", ["cy_test.pyx","test.c"])])
setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
include_dirs=[np.get_include()]
)
I think that my problem may come from the same reason as in the github link but I don't see how to solve it (in my case the C pointer already exist so I think I can't use the same solution).
I work on Windows 10 with Anaconda 64bits, here are the detail of the version: 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]