Python Cython:通过引用传递 问题
我想通过引用Cython中的函数来传递一个向量 “MyClass.h”命名空间“MyClass”中的cdef外部名: void MyClass_doStuff“MyClass::doStuff”(向量[double]&输入)除了+ cdef类MyClass: ... @静力学方法 def DOSTUF(矢量[双]&输入): MyClass_doStuff(输入) 问题: 上面的代码在编译过程中不会抛出错误,但也不起作用<代码>输入在方法之后保持不变。 我也尝试过这个建议,但在本例中,Python Cython:通过引用传递 问题,python,c++,pass-by-reference,cython,Python,C++,Pass By Reference,Cython,我想通过引用Cython中的函数来传递一个向量 “MyClass.h”命名空间“MyClass”中的cdef外部名: void MyClass_doStuff“MyClass::doStuff”(向量[double]&输入)除了+ cdef类MyClass: ... @静力学方法 def DOSTUF(矢量[双]&输入): MyClass_doStuff(输入) 问题: 上面的代码在编译过程中不会抛出错误,但也不起作用输入在方法之后保持不变。 我也尝试过这个建议,但在本例中,cdef-函数将无
cdef
-函数将无法从Python访问(“未知成员doStuff…”)
是否可以通过引用进行传递?如果可以,如何正确传递
编辑
这不是我在上面一节中提到的问题的副本。建议的解决方案没有实现我的目标,即让python函数通过引用获取参数。问题 正如Kevin和jepio在对您的问题的评论中所说,问题在于如何在Python中处理向量。Cython确实定义了一个cpp向量类,该类会自动转换为Cython代码边界处的列表或从列表转换为Cython代码 问题在于转换步骤:调用函数时:
def doStuff(vector[double]& input):
MyClass_doStuff(input)
被转化为接近
def doStuff(list input):
vector[double] v= some_cython_function_to_make_a_vector_from_a_list(input)
MyClass_doStuff(input)
# nothing to copy the vector back into the list
答案
我想你有两个选择。第一种方法是完整地写出流程(即,制作两份手册副本):
这对于大向量来说会很慢,但对我来说很有效(我的测试函数是v.push_back(10.0)
):
第二个选项是定义您自己的包装器类,它直接包含一个vector[double]
cdef class WrappedVector:
cdef vector[double] v
# note the absence of:
# automatically defined type conversions (e.g. from list)
# operators to change v (e.g. [])
# etc.
# you're going to have to write these yourself!
然后写
def doStuff(WrappedVector input):
MyClass_doStuff(input.v)
您计划如何在Python中构建
向量
的可能重复?因为这是唯一允许调用该函数的东西…您希望如何从python代码中传入向量?Cython定义了一个cpp向量类来使用。在python级别上,列表可以正常工作。有关详细信息,请参阅。
cdef class WrappedVector:
cdef vector[double] v
# note the absence of:
# automatically defined type conversions (e.g. from list)
# operators to change v (e.g. [])
# etc.
# you're going to have to write these yourself!
def doStuff(WrappedVector input):
MyClass_doStuff(input.v)