cython中的空数组:调用PyArray_EMPTY时的段错误

sta*_*icd 5 python arrays numpy cython

当我尝试运行下面的cython代码生成一个空数组时,就会出现段错误.

有没有办法在python中生成空的numpy数组而不调用np.empty()

cdef np.npy_intp *dims = [3]
cdef np.ndarray[np.int_t, ndim=1] result = np.PyArray_EMPTY(1, dims, 
                                                            np.NPY_INTP, 0)
Run Code Online (Sandbox Code Playgroud)

War*_*ser 3

您可能很久以前就已经解决了这个问题,但是为了任何在试图找出 cython 代码段错误原因时偶然发现这个问题的人的利益,这里有一个可能的答案。

当您在使用 numpy C API 时遇到段错误时,首先要检查的是您是否调用了该函数import_array()。这可能就是问题所在。

例如,这里是foo.pyx

cimport numpy as cnp


cnp.import_array()  # This must be called before using the numpy C API.

def bar():
    cdef cnp.npy_intp *dims = [3]
    cdef cnp.ndarray[cnp.int_t, ndim=1] result = \
        cnp.PyArray_EMPTY(1, dims, cnp.NPY_INTP, 0)
    return result
Run Code Online (Sandbox Code Playgroud)

这是setup.py构建扩展模块的简单方法:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np


setup(cmdclass={'build_ext': build_ext},
      ext_modules=[Extension('foo', ['foo.pyx'])],
      include_dirs=[np.get_include()])
Run Code Online (Sandbox Code Playgroud)

这是正在运行的模块:

In [1]: import foo

In [2]: foo.bar()
Out[2]: array([4314271744, 4314271744, 4353385752])

In [3]: foo.bar()
Out[3]: array([0, 0, 0])
Run Code Online (Sandbox Code Playgroud)