Cython amp; C++: passing by reference(Cython amp;C++:通过引用传递)
问题描述
我是 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++:通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Cython &C++:通过引用传递
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01