2013-08-26 33 views
5

當我嘗試運行下面的cython代碼以生成一個空數組時,它會發生segfaults。cython中的空數組:調用PyArray_EMPTY時發生segfault

有沒有什麼辦法可以在不調用np.empty()的情況下在python中生成空numpy數組?

cdef np.npy_intp *dims = [3] 
cdef np.ndarray[np.int_t, ndim=1] result = np.PyArray_EMPTY(1, dims, 
                  np.NPY_INTP, 0) 
+0

什麼是錯的np.empty()?如果你在初始化階段只做一次,你不會在意它比直接使用C函數稍微慢一些。 –

+2

如果您對大小<1000的數組執行操作,則單獨使用np.empty()的成本大於整個循環。請參閱(http://stackoverflow.com/questions/18410342/creating-small-arrays-in-cython-takes-a-humongous-amount-of-time)我在哪裏描述了這個問題。我試圖解決它,但現在發現了一個新問題:即使用np.PyArray_EMPTY()函數 – staticd

+1

np.NPY_INTP和np.int_t是您系統中的相同類型嗎? – Jaime

回答

1

你可能已經是很久以前解決這一點,但對任何人的誰碰到這個問題絆倒在試圖搞清楚爲什麼他們用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])