我试图在 cython 类中启动一个固定大小的数组,以便多种方法可以使用它。怎么做?
cdef class My Class:
cdef public np.ndarray[np.float, ndim=1] myarr
def __cinit__(self,int history_length):
self.myarr = np.empty(history_length, dtype=np.float)
我收到一条错误消息:
buffer types only allowed as function local variables
有没有办法声明并访问它?
谢谢
答案 0 :(得分:2)
我相信缓冲区语法类型 [::1] 在 cython 中是首选的,即
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef float[::1] myarr
def __cinit__(self,int history_length):
self.myarr = np.empty(history_length, dtype=np.float)
编辑:上面的代码假设您在内存中定义了一个连续的数组,默认情况下,对于 numpy 数组,它是 c 样式(即行连续)。定义它 float[:] 会表明您期望浮点缓冲区不一定是连续的。