如何通过Python/C API将Python实例传递给C++

Den*_*ard 6 c++ python swig python-2.7

我通过使用SWIG 2.0包装接口来扩展我的Python(2.7)库,并有一个图形对象,我想在其中创建一个访问者.在C++中,界面如下所示:

    struct Visitor
    {
        virtual void OnStateBegin() = 0;
        virtual void OnNode(Node* n) = 0;
        virtual void OnStateEnd() = 0;
    };
Run Code Online (Sandbox Code Playgroud)

我想在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)
Run Code Online (Sandbox Code Playgroud)

我要做的是在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++?
Run Code Online (Sandbox Code Playgroud)

在我用Swig包装的C++中,我不确定如何获取实例'mvis'?我可以调用Python中定义的函数没问题,但是实例让我难过!

Chr*_*ger 0

我不知道 SWIG 是否可行,但您可以使用SIP做到这一点。

sip_vector_test.h:

class EXPORT Node {
public:
    explicit Node(int n) : n_(n) {};
    int getN() const { return n_; }
private:
    int n_;
};
struct EXPORT NodeVisitor {
    virtual void OnNode(Node* n) = 0;
};
struct EXPORT Graph {
public:
    void addNode(int num);
    void accept(NodeVisitor *nv);
private:
    std::vector< std::shared_ptr<Node> > nodes_;
};
Run Code Online (Sandbox Code Playgroud)

访客.sip:

%Module pyvisit

%ModuleHeaderCode
#include "sip_visitor_test.h"
%End

class Node {
public:
    explicit Node(int n);
    int getN() const;
};
struct NodeVisitor {
    virtual void OnNode(Node* n) = 0;
};
struct Graph {
public:
    void addNode(int num);
    void accept(NodeVisitor *nv);
};
Run Code Online (Sandbox Code Playgroud)

从 Python 使用它:

>>> import pyvisit
>>> g = pyvisit.Graph()
>>> g.addNode(3)
>>> g.addNode(5)
>>> class PyNodeVisitor(pyvisit.NodeVisitor):
>>>     def OnNode(self, node):
>>>         print(node.getN())
>>> pnv = PyNodeVisitor()
>>> g.accept(pnv)
3
5
Run Code Online (Sandbox Code Playgroud)

我已将包含此测试项目源代码的zip 文件放在我的主页上。