25

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

richizy
  • 2,002
  • 3
  • 21
  • 26
  • 1
    Somewhat related question on [cython-users](https://groups.google.com/forum/#!forum/cython-users): ["Question about pass-by-reference"](https://groups.google.com/forum/#!topic/cython-users/6c2ixr4xEZA) – iljau Feb 12 '14 at 07:51

1 Answers1

24

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)
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
richizy
  • 2,002
  • 3
  • 21
  • 26
  • i do pass-by-ref for std::string but can't change its value inside the function – Dee Nov 18 '21 at 09:57