【发布时间】:2015-04-28 19:20:10
【问题描述】:
我通过使用 SWIG 2.0 包装接口来使用 Python (2.7) 扩展我的库,并有一个我想在其中创建访问者的图形对象。在 C++ 中,界面如下所示:
struct Visitor
{
virtual void OnStateBegin() = 0;
virtual void OnNode(Node* n) = 0;
virtual void OnStateEnd() = 0;
};
我想在 Python 中定义一个等效的类,全部在 python 中定义,允许定义访问者:
class GraphVisitor:
def __init__(self, label):
self._label = label
print("__init__(self,{0})".format(self._label))
def OnStateBegin(self):
print("OnStateBegin()" + self._label)
def OnNode(self, i_node):
print("OnNode()" + self._label)
def OnStateEnd(self):
print("OnStateEnd()" + self._label)
我要做的是在 python 脚本中创建一个 GraphVisitor 的实例,并从 C++ 中为给定的实例调用 OnStateBegin()、OnNode() 和 OnStateEnd() 方法。这是我想在 Python 中做的事情:
#model is a SWIG wrapped class
mvis = GraphVisitor("This is a test")
model.Visit("mvis") # I'm not sure how to pass the instance 'mvis' to C++?
在我由 Swig 包装的 C++ 中,我不确定如何获取实例“mvis”?我可以调用 Python 中定义的函数没问题,但实例让我很难过!
【问题讨论】:
-
mvis只是 python 类的一个实例。它与您的struct Visitor有关。在 C/C++ 中,您只能以PyObject*的形式访问它。 -
我知道。我试图描述我正在尝试在 python 中定义一个访问者,而这就是 c++ 对应项。
-
你看过我之前的回答了吗:stackoverflow.com/questions/9040669/…(你可以跳过关于嵌入的部分,但是关于从 PyObject 转换为 C++ 接口的部分正是你想要的)
-
柔印 - 非常感谢!你的东西真的很有帮助!
标签: python c++ python-2.7 swig