Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython & C++: passing by reference

I am a noob with Cython and C++, so I have a question on argument passing. I want to avoid passing a copy of an argument in the following scenario:

# somefile.pyx
#distutils: language = c++
from libcpp.vector cimport vector

def add_one(vector[int] vect):
    cdef int i
    n = vect.size()
    for i in range(n):
        vect[i] += 1

cdef vector[int] v
for i in range(100000):
    v.push_back(i)
add_one(v) # <-- ??

I want the method add_one to just modify v "in-place." I believe in C++, you can achieve this by pre-pending the argument with &, which means that any changes to the pointer is passed to the pointee. That way, you don't have to worry about passing a pointer or the actual object, i.e.

add_one(v); # in c++

Can I do the same in Cython, or do I have to explicitly change the arg type to a reference instead, i.e. def add_one(vector[int]* vect)?

like image 359
richizy Avatar asked Feb 12 '14 07:02

richizy


People also ask

How much faster is Cython than Python?

Note that regular Python takes more than 500 seconds for executing the above code while Cython just takes around 1 second. Thus, Cython is 500x times faster than Python for summing 1 billion numbers.

Can Cython be as fast as C?

Cython code runs fastest when “pure C” If you have a function in C labeled with the cdef keyword, with all of its variables and inline function calls to other things that are pure C, it will run as fast as C can go.

Is Cython included with Python?

The Cython language is a superset of the Python language (almost all Python code is also valid Cython code), but Cython additionally supports optional static typing to natively call C functions, operate with C++ classes and declare fast C types on variables and class attributes.

Is Cython and CPython the same?

CPython is the implementation of the language called “Python” in C. Python is an interpreted programming language. Hence, Python programmers need interpreters to convert Python code into machine code. Whereas Cython is a compiled programming language.


1 Answers

Found the answer to my own question. Apparently, you can pass by reference, but the function MUST be cdef'ed, not def'ed. i.e.

# somefile.pyx #distutils: language = c++ from libcpp.vector cimport vector  cdef void add_one(vector[int]& vect):     cdef int i     n = vect.size()     for i in range(<int>n):         vect[i] += 1  cdef vector[int] v for i in range(100000):     v.push_back(i) add_one(v) 
like image 162
richizy Avatar answered Sep 22 '22 15:09

richizy