接口定义中只有一些小错误。以下为我工作:
from libc.stdlib cimport mallocimport numpy as npcimport numpy as npnp.import_array()ctypedef np.int32_t DTYPE_tcdef 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 arrdef test(): N = 1000 cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t)) arr = data_to_numpy_array_with_spec(data, N, np.NPY_INT32) return arr
这是我的
setup.py文件:
from distutils.core import setup, Extensionfrom Cython.Distutils import build_extext_modules = [Extension("_owndata", ["owndata.pyx"])]setup(cmdclass={'build_ext': build_ext}, ext_modules=ext_modules)用构建
python setup.py build_ext --inplace。然后验证数据是实际拥有的:
import _owndataarr = _owndata.test()print arr.flags
除其他外,您应该看到
OWNdata: True。
而且 是 ,这绝对是处理这个正确的方式,因为
numpy.pxd究竟到所有其他功能导出到用Cython同样的事情。



