我想從Python調用我的C函數,以便操縱一些NumPy數組。功能是這樣的:在Cython和NumPy中包裝C函數
void c_func(int *in_array, int n, int *out_array);
,其中結果在out_array,其大小我知道事先提供的(不是我的功能,實際上)。我嘗試做相應.pyx文件中的以下,爲了能夠從與NumPy陣列通過輸入功能,並把結果存儲在一個與NumPy陣列:
def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array):
n = len(in_array)
out_array = np.zeros((512,), dtype = np.int32)
mymodule.c_func(<int *> in_array.data, n, <int *> out_array.data)
return out_array
,但我得到 "Python objects cannot be cast to pointers of primitive types"
輸出分配錯誤。我該如何做到這一點?
(如果我需要Python的調用者分配適當的輸出數組,然後我可以做
def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array, np.ndarray[np.int32_t, ndim=1] out_array):
n = len(in_array)
mymodule.cfunc(<int *> in_array.data, n, <int*> out_array.data)
但我能做到這一點的方式,調用者不必預先分配適當大小輸出數組?
沒請您儘量提供補充'CDEF np.ndarray'之前'out_array' assignement? – Simon 2012-04-08 17:58:01
工作,謝謝! – Peter 2012-04-08 18:07:57