【发布时间】:2014-01-08 14:55:50
【问题描述】:
我正在尝试使用 Cython 包装一个 C++ 模块,以便我可以在 Python 中使用它。
该模块有多个类,其中一些具有将对象引用作为参数的另一个类的方法。
假设我有名为“foo”和“bar”的 c++ 类,而 cython 将它们包装起来:
cdef extern from "foobar.hpp" namespace "foobar":
cdef cppclass foo:
pass
cdef cppclass bar:
void kungFoo(foo &f)
现在我想创建一个包装类,以便可以在 Python 中使用它...
cdef class pyFoo:
cdef foo *thisptr
def __cinit__(self):
self.thisptr = new foo()
cdef class pyBar:
cdef bar *thisptr
def __cinit__(self):
self.thisptr = new bar()
def kungFoo(self, f):
self.thisptr.kungFoo(f.thisptr)
这会导致“编译 Cython 文件时出错”。和“无法将 Python 对象转换为 'foo'”。
我认为这是因为 cdef cppclass foo 使 foo 成为与 c++ 类关联的“Python 对象”。然而,当我需要将它作为参数传递给另一个 c++ 类时,这种巧妙的转换似乎并没有反过来。
对我来说,这似乎是 cython 的一个基本问题 - 但在谷歌上几个小时后我似乎无法找到任何解决方案。
欢迎任何帮助。
谢谢!
【问题讨论】:
-
嗯-我尝试了以下方法: self.thisptr.kungFoo(
f.thisptr) 并且编译正确。不幸的是,运行结果会导致分段错误。
标签: python c++ cython python-2.x