python - Cython 缓冲协议(protocol)示例错误

标签 python c++ cython

我正在尝试这个 url 上的示例。 http://cython.readthedocs.io/en/latest/src/userguide/buffer.html

为了测试它,我执行以下操作。

import pyximport
pyximport.install(build_dir = 'build')
import ctest

m = ctest.Matrix(10)
m.add_row()
print(m)

当我调用 m.add_row() 函数时,这给了我一个错误 TypeError: 'int' 对象不可迭代

在类中add_row定义为

from cpython cimport Py_buffer
from libcpp.vector cimport vector

cdef class Matrix:
    cdef Py_ssize_t ncols
    cdef Py_ssize_t shape[2]
    cdef Py_ssize_t strides[2]
    cdef vector[float] v

    def __cinit__(self, Py_ssize_t ncols):
        self.ncols = ncols

    def add_row(self):
        """Adds a row, initially zero-filled."""
        self.v.extend(self.ncols)
    ...

假设在 cython 中对 vector 调用 extend 与在 python 列表上调用 extend 完全相同,这个错误对我来说完全有意义。您不会传递给它一个数字,而是一个附加到列表的可迭代对象。

我可以通过这样做来修复它...

def add_row(self):
    """Adds a row, initially zero-filled."""
    self.v.extend([0] * self.ncols)

我只是想知道示例中是否有错字,或者我是否遗漏了什么。另外, vector 的扩展函数从哪里来?在用 cython 分发的 vector.pxd 文件中,它从不导入扩展函数,甚至在 c++ 标准库中也不存在。 cython 是否对 vector 类型做了一些特殊的事情?

https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/vector.pxd

最佳答案

cpp vector可以自动转换为python列表。通过检查 self.v.extend([0] * self.ncols) 行的 c 代码,创建了一个新的 python 列表:__pyx_t_2 = PyList_New(1 * ((__pyx_v_self->ncols<0) ? 0:__pyx_v_self->ncols)) .因此 extend实际上是 extend python列表的方法。

这种自动转换也可以通过以下代码验证(在jupyter notebook中):

%%cython -+
from libcpp.vector cimport vector

def test_cpp_vector_to_pylist():
    cdef vector[int] cv
    for i in range(10):
        cv.push_back(i)
    return cv

a = test_cpp_vector_to_pylist()
print a       # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print type(a) # <type 'list'>

然而,cv在这种情况下被转换为一个临时的python列表,原始cpp vertor将保持不变,如下代码所示:

%%cython -+
from libcpp.vector cimport vector

def test_cpp_vector_to_pylist_1():
    cdef vector[int] cv
    for i in range(10):
        cv.append(i)    # Note: the append method of python list 
    return cv

a = test_cpp_vector_to_pylist_1()
print a       # []
print type(a) # <type 'list'>

另外,一个c数组也可以自动转成python列表:

%%cython

def test_c_array_to_pylist():
    cdef int i
    cdef int[10] ca
    for i in range(10):
        ca[i] = i
    return ca

a = test_c_array_to_pylist()
print a       # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print type(a) # <type 'list'>

关于python - Cython 缓冲协议(protocol)示例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170532/

相关文章:

Python 3D插值加速

python - 当 x 值为日期时间时,如何使用 polyfit 获得最佳拟合曲线?

python - push 部署工作,配置 "release pipeline"

python - Python中如何快速得到线性规划的可行解?

python - 如何在 aws ec2 实例上安装 python3.6

C++ 类(组合和继承 - 头文件、类数组)

C++ 三元运算符逻辑

c++ - VC++调试未初始化变量的方法

python - 如何测试 Cython 属性是否为生成器?

python - Cython 中的继承(简短的示例代码)