Cython Buffer Protocol Example Error

I am trying an example at this url. http://cython.readthedocs.io/en/latest/src/userguide/buffer.html

To verify this, I do the following.

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

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

This gives me an error when I call the m.add_row () function, saying TypeError: 'int' object is not iterable

In the class add_row is defined as

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)
    ...

This error has full meaning to me, assuming that calling extend on a vector in cython does the same thing as in a python list. You do not pass a number to it, but an iterable object that is added to the list.

I can fix it by doing this ...

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

, - . ? vector.pxd, cython, ++. Cython - ?

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

+4
1

Cpp vector python. c self.v.extend([0] * self.ncols), python: __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->ncols<0) ? 0:__pyx_v_self->ncols)). , extend extend python.

( jupyter):

%%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 , :

%%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'>
+2

Source: https://habr.com/ru/post/1669432/


All Articles