将`cimport numpy`添加到pyx文件编译好,但在运行时抛出ValueError

时间:2012-10-24 01:51:22

标签: python build numpy cython

我正在尝试优化我编写的一个简单的cython例程,该例程接受一维numpy数组作为输入并返回一维numpy数组作为输出。

我有一个天真的版本,我现在正试图对cython代码的numpy部分做一些standard optimisations

但是,只要我将cimport numpy添加到我的cython源文件中,我就无法运行扩展模块(虽然编译好了),抛出ValueError: numpy.dtype does not appear to be the correct type object

我的numpy版本是1.6.0和python版本2.6.5(默认,Ubuntu 10.04 apt-get安装)

导致问题的最小示例:


test_ext.pyx

import numpy as np
cimport numpy as np #Commenting this line un-breaks the extension

def test_ext(refls, str mode, int nguard, int nblock):

    cdef int i
    cdef int _len = refls.shape[0]
    _out = np.zeros([_len])

    for i in range(_len):
        _out[i] = refls[i] + 1
    return _out

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("test_ext", ["test_ext.pyx"])]

setup(
    name = 'test',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)

run_ext.py

import numpy
from test_ext import test_ext

a = np.array([x for x in range(260)])
_res = test_ext.test_ext(a, 'avg', 2, 3)

使用:

构建

python setup.py build_ext --inplace

我的构建输出:

running build_ext
cythoning my_ext.pyx to my_ext.c
building 'my_ext' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c my_ext.c -o build/temp.linux-x86_64-2.6/my_ext.o
/usr/include/python2.6/numpy/__multiarray_api.h:968: warning: ‘_import_array’ defined but not used
my_ext.c:732: warning: ‘__pyx_k_3’ defined but not used
my_ext.c:733: warning: ‘__pyx_k_4’ defined but not used
my_ext.c:753: warning: ‘__pyx_k_24’ defined but not used
my_ext.c:759: warning: ‘__pyx_k_26’ defined but not used
my_ext.c:760: warning: ‘__pyx_k_27’ defined but not used
my_ext.c:1118: warning: ‘__pyx_pf_5numpy_7ndarray___getbuffer__’ defined but not used
my_ext.c:1876: warning: ‘__pyx_pf_5numpy_7ndarray___releasebuffer__’ defined but not used
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-x86_64-2.6/my_ext.o -o /home/path/to/my_ext.so

然后运行run_ext.py

取消注释cimport行,我收到错误:

Traceback (most recent call last):
  File "run_ext.py", line 2, in <module>
    from test_ext import test_ext
  File "numpy.pxd", line 43, in test_ext (test_ext.c:2788)
ValueError: numpy.dtype does not appear to be the correct type object

导致此问题的原因是什么?我如何修复它以继续优化我的扩展程序?我已经尝试按照上面的链接继续进行优化,但是无论如何,对我来说,没有什么可以解决这个问题。

我见过其他一些有这个问题的人有python / numpy的版本问题,但我不认为对我来说就是这种情况(尽管我很乐意在那里提出建议)。任何建议表示赞赏。

1 个答案:

答案 0 :(得分:3)

看起来我的构建文件只需要包含numpy包含文件。将setup.py更改为以下内容:

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy   # << New line

ext_modules = [Extension("test_ext", ["test_ext.pyx"])]

setup(
    name = 'test',
    cmdclass = {'build_ext': build_ext},
    include_dirs = [numpy.get_include()], # << New line
    ext_modules = ext_modules
)