Python cython中的空数组:调用PyArray\u empty时出现segfault

Python cython中的空数组:调用PyArray\u empty时出现segfault,python,arrays,numpy,cython,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) 您可

当我试图运行下面的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)

您可能早就解决了这个问题,但对于那些在试图找出cython代码错误原因时偶然发现这个问题的人来说,这里有一个可能的答案

当您在使用numpy C API时遇到segfault时,首先要检查的是您是否调用了函数
import\u 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
下面是一个用于构建扩展模块的简单的
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()])
以下是正在运行的模块:

In [1]: import foo

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

In [3]: foo.bar()
Out[3]: array([0, 0, 0])

np.empty()有什么问题吗?如果在初始化阶段只执行一次,则不必关心它是否比直接使用C函数稍微慢一点。如果在大小为
np.NPY\u INTP
np.int\u t
的数组上执行操作,那么第一行是否真的正确?对我来说这似乎是可疑的。