问题
我想通过引用Cython中的函数传递一个向量。
cdef extern from "MyClass.h" namespace "MyClass":
void MyClass_doStuff "MyClass::doStuff"(vector[double]& input) except +
cdef class MyClass:
...
@staticmethod
def doStuff(vector[double]& input):
MyClass_doStuff(input)问题
上面的代码在编译过程中不会抛出错误,但也不起作用。input在该方法之后就没有变化了。我也尝试过建议in this question,但在本例中,cdef-function将无法从-function访问(“未知成员doStuff.”)。
是否可能通过引用传递,如果可能,如何正确地进行?
编辑
这不是cython-c-passing-by-reference的副本,因为我在上面一节中提到了这个问题。所建议的解决方案没有完成我的目标,即让python函数引用一个参数。
发布于 2015-03-31 07:26:03
问题
正如Kevin和jepio在对您的问题的评论中所指出的,问题在于您如何处理Python中的向量。Cython确实定义了一个cpp向量类,它将自动转换为/从边界处的列表转换为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的答案
我想你有两个选择。第一种方法是将整个过程写出来(即两份手册):
def doStuff(list input):
cdef vector[double] v = input
MyClass_doStuff(v)
input[:] = v对于大型向量来说,这将是缓慢的,但对我来说是有效的(我的测试函数是v.push_back(10.0)):
>>> l=[1,2,3,4]
>>> doStuff(l)
>>> l
[1.0, 2.0, 3.0, 4.0, 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)https://stackoverflow.com/questions/29356403
复制相似问题