问题描述
我是Cython和C ++的noob,所以我有一个关于参数传递的问题。我想避免在以下场景中传递参数的副本:
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) # <-- ??
我想要方法 add_one
v
就地。我相信在C ++,你可以通过预先挂起参数&
来实现这一点,这意味着对指针的任何更改都传递给了pointee。这样,你不必担心传递指针或实际对象,即
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++
我可以在Cython中做同样的事, def add_one(vector [int] * vect)
?
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)
?
推荐答案
找到了我自己的问题。显然,你可以通过引用传递,但是函数必须是 cdef
'ed,而不是 def
'ed。即
Found the naswer 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)
这篇关于Cython& C ++:通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!