问题描述
我想要一个带有NumPy成员的Cython"cdef"对象,并能够使用快速缓冲区访问.理想情况下,我会做类似的事情:
I want to have a Cython "cdef" object with a NumPy member, and be able to use fast buffer access. Ideally, I would do something like:
import numpy as np
cimport numpy as np
cdef class Model:
cdef np.ndarray[np.int_t, ndim=1] A
def sum(self):
cdef int i, s=0, N=len(self.A)
for 0 <= i < N:
s += self.A[i]
return s
def __init__(self):
self.A = np.arange(1000)
不幸的是,Cython无法编译它,错误为Buffer types only allowed as function local variables
.
Unfortunately, Cython can't compile this, with the error Buffer types only allowed as function local variables
.
我正在使用的解决方法是在分配给对象成员的新局部变量上声明缓冲区属性:
The workaround I'm using is to declare the buffer attributes on a new local variable, assigned to the object member:
cdef class Model:
cdef np.ndarray A
def sum(self):
cdef int i, s=0, N=len(self.A)
cdef np.ndarray[np.int_t, ndim=1] A = self.A
for 0 <= i < N:
s += A[i]
return s
如果您想让多个方法访问相同的数据结构,这将变得非常烦人-这似乎是一个非常普遍的用例,不是吗?
This becomes really annoying if you want to have multiple methods accessing the same data structures -- which seems like a pretty common use case, no?
是否有更好的解决方案,不需要在每个方法中重新声明类型?
Is there a better solution that doesn't require re-declaring the types inside every method?
推荐答案
可以选择使用内存片或cython数组 http://docs.cython.org/src/userguide/memoryviews.html
There is the option to work with memory slices or cython arrayshttp://docs.cython.org/src/userguide/memoryviews.html
import numpy as np
cimport numpy as np
cdef class Model:
cdef int [:] A
def sum(self):
for 0 <= i < N:
s += self.A[i]
return s
def __init__(self):
self.A = np.arange(1000)
这篇关于对象成员的Cython缓冲区声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!