我了解 C 和 Python,但我是 Cython 的新手。
我对一个(连续的)双精度数组有一个看法。我想通过指针和索引遍历视图的项目,就像我们在 C 中所做的那样。但是,我无法用 Cython 表达:
from cpython cimport array
import array
arr = array.array("d", (1,2,3,4))
cdef double[::1] view = arr[::1]
cdef unsigned l = len(view)
cdef double *ptr = view.as_doubles
# Iterate over the view items
cdef double acc = 0.0
cdef unsigned i
for i in range(l):
acc += ptr[i]
上面的代码被错误拒绝:
a.pyx:8:5: Storing unsafe C derivative of temporary Python reference
我该如何解决?
acc += view[i]
在这里涉及指针真的没有意义 - 索引类型化的内存视图应该具有可比的性能。 (如果您确定在索引时不需要它们,您可能希望使用适当的 Cython 编译器指令禁用
boundschecking
和 wraparound
)
我将(非类型化)数组的语法与
....as_doubles
和(类型化)内存视图的语法混合在一起。
正确的代码应该是:
cdef double *ptr = &view[0]