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

时间:2013-08-26 08:24:14

标签: 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)

1 个答案:

答案 0 :(得分:2)

很久以前你可能已经解决了这个问题,但是为了让任何偶然发现这个问题的人在试图找出他们的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

这是一个简单的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])
相关问题