gpt4 book ai didi

python - 对象成员的 Cython 缓冲区声明

转载 作者:IT老高 更新时间:2023-10-28 20:41:32 25 4
gpt4 key购买 nike

我想要一个带有 NumPy 成员的 Cython“cdef”对象,并且能够使用快速缓冲区访问。理想情况下,我会这样做:

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.

我使用的解决方法是在分配给对象成员的新局部变量上声明缓冲区属性:

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

如果您想让多个方法访问相同的数据结构,这会变得非常烦人——这似乎是一个很常见的用例,不是吗?

有没有更好的解决方案,不需要在每个方法中重新声明类型?

最佳答案

可以选择使用内存片或 cython 数组 http://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)

关于python - 对象成员的 Cython 缓冲区声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8808216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com