问题描述
我是 Cython 和 C++ 的菜鸟,所以我有一个关于参数传递的问题.我想避免在以下场景中传递参数的副本:
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++ 中,您可以通过在参数前面加上 &
来实现这一点,这意味着对指针的任何更改都会传递给被指点者.这样,您就不必担心传递指针或实际对象,即
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 中做同样的事情,还是必须明确地将 arg 类型更改为引用,即 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 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)
这篇关于Cython &C++:通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!