【发布时间】:2014-07-15 09:27:12
【问题描述】:
在this answer to "Can I force a numpy ndarray to take ownership of its memory?" 之后,我尝试通过 Cython 的 NumPy 包装器使用 Python C API 函数 PyArray_ENABLEFLAGS,发现它没有暴露。
以下尝试手动公开它(这只是重现失败的最小示例)
from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.int32_t DTYPE_t
cdef extern from "numpy/ndarraytypes.h":
void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags)
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t))
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, np.NPY_INT32, data)
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA)
因编译错误而失败:
Error compiling Cython file:
------------------------------------------------------------
...
def test():
cdef int N = 1000
cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t))
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &N, np.NPY_INT32, data)
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA)
^
------------------------------------------------------------
/tmp/test.pyx:19:27: Cannot convert Python object to 'PyArrayObject *'
我的问题:这是在这种情况下采取的正确方法吗?如果是这样,我做错了什么?如果没有,我如何强制 NumPy 获得 Cython 的所有权,而不需要深入到 C 扩展模块?
【问题讨论】:
-
我的回答对你有用吗?
-
确实做到了,谢谢!
标签: python arrays numpy cython