Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python List to Vector<int> in Cython

Tags:

python

cython

I need to convert a Python list of ints to vector[int] in a cdef function to call another C function. I tried this:

cdef pylist_to_handles(hs):
    cdef vector[int] o_vect
    for h in hs:
        o_vect.push_back(h)
    return o_vect

This should work because I only need to call this from other cdef functions, but I get this error:

Cannot convert 'vector<int>' to Python object

What am I doing wrong ?

like image 231
iabdalkader Avatar asked Dec 06 '22 13:12

iabdalkader


2 Answers

In Cython 0.17 using libcpp.vector, you can do this:

cdef vector[int] vect = hs
like image 64
Stefan Behnel Avatar answered Dec 22 '22 17:12

Stefan Behnel


What you really have is this:

cdef object pylist_to_handles(hs):
    ...
    return <object>o_vect

If you do not explicitily set a type, it is assumed to be a python object ("object" in code). As you see in the code, you're trying to cast vector[int] to an object, but Cython does not know how to handle that.

Just add a return type in cdef:

cdef vector[int] pylist_to_handles(hs):
like image 45
Czarek Tomczak Avatar answered Dec 22 '22 17:12

Czarek Tomczak