我有以下代码,它实现了一个带有Python回调函数的简单C ++类(ObjWithPyCallback)。我们的想法是用“this”作为单个参数调用Python函数。
问题在于,由于ObjWithPyCallback是一个SWIG包装的对象,我需要SWIG typeinfo才能创建一个Python对象。
这个问题是它在SWIG生成的文件“ObjWithPyCallback_wrap.cxx”中。 SWIG可以生成头文件吗?到目前为止,我还未能实现这一目标。
然而,即使有一个头文件,SWIG和我的主要实现之间也存在循环依赖关系,这很烦人。如果可能的话,我想找到一种方法来避免它。最终,ObjWithPyCallback最终存在于与Python绑定不同的共享库中。
有没有一种干净的方式来解决这个问题?我知道this post,但它只涉及SWIG_NewPointerObj的机制。
提前感谢您的帮助!
以下是代码:
文件:example.py
import cb
def foo(x=None):
print("Hello from Foo!")
# I'd like x to be a reference to a ObjWithPyCallback object.
print(x)
o = cb.ObjWithPyCallback()
o.setCallback(foo)
o.call()
文件:ObjWithPyCallback.h
#include <Python.h>
class ObjWithPyCallback
{
public:
ObjWithPyCallback();
void setCallback(PyObject *callback);
void call();
PyObject *callback_;
};
文件:ObjWithCallback.cpp
#include "ObjWithPyCallback.h"
#include <iostream>
ObjWithPyCallback::ObjWithPyCallback() : callback_(NULL) {}
void ObjWithPyCallback::setCallback(PyObject* callback)
{
if (!PyCallable_Check(callback))
{
std::cerr << "Object is not callable.\n";
}
else
{
if ( callback_ ) Py_XDECREF(callback_);
callback_ = callback;
Py_XINCREF(callback_);
}
}
void ObjWithPyCallback::call()
{
if ( ! callback_ )
{
std::cerr << "No callback is set.\n";
}
else
{
// I want to call "callback_(*this)", how to do this cleanly?
PyObject *result = PyObject_CallFunction(callback_, "");
if (result == NULL)
std::cerr << "Callback call failed.\n";
else
Py_DECREF(result);
}
}
File :: ObjWithPyCallback.i
%module cb
%{
#include "ObjWithPyCallback.h"
%}
%include "ObjWithPyCallback.h"
答案 0 :(得分:12)
以下是解决此问题的解决方法。它使用了@omnifarious和@flexo上面的建议。
特别是我们使用SWIG导向器创建一个Callback类,然后在Python中派生它以获得所需的回调功能,而不会引入循环依赖。
此外,我们提供了一个接口,允许任何可调用的Python对象充当回调。我们通过在SWIG中使用“pythonprend”指令来实现这一点,以便将一些代码添加到“setCallback”函数中。此代码只检查可调用对象,如果找到,则将其包装在Callback实例中。
最后,我们处理与使用C ++类(ObjWithPyCallback)引用导向器对象(即Callback的子类)相关的内存问题。
文件example.py:
import cb
class CB(cb.Callback):
def __init__(self):
super(CB, self).__init__()
def call(self, x):
print("Hello from CB!")
print(x)
def foo(x):
print("Hello from foo!")
print(x)
class Bar:
def __call__(self, x):
print("Hello from Bar!")
print(x)
o = cb.ObjWithPyCallback()
mycb=CB()
o.setCallback(mycb)
o.call()
o.setCallback(foo)
o.call()
o.setCallback(Bar())
o.call()
文件ObjWithPyCallback.i:
%module(directors="1") cb
%{
#include "Callback.h"
#include "ObjWithPyCallback.h"
%}
%feature("director") Callback;
%feature("nodirector") ObjWithPyCallback;
%feature("pythonprepend") ObjWithPyCallback::setCallback(Callback&) %{
if len(args) == 1 and (not isinstance(args[0], Callback) and callable(args[0])):
class CallableWrapper(Callback):
def __init__(self, f):
super(CallableWrapper, self).__init__()
self.f_ = f
def call(self, obj):
self.f_(obj)
args = tuple([CallableWrapper(args[0])])
args[0].__disown__()
elif len(args) == 1 and isinstance(args[0], Callback):
args[0].__disown__()
%}
%include "Callback.h"
%include "ObjWithPyCallback.h"
文件Callback.h:
#ifndef CALLBACK_H
#define CALLBACK_H
class ObjWithPyCallback;
class Callback
{
public:
Callback(){}
virtual ~Callback(){}
virtual void call(ObjWithPyCallback& object){}
};
#endif
文件ObjWithPyCallback.h:
#ifndef OBJWITHPYCALLBACK_H
#define OBJWITHPYCALLBACK_H
class Callback;
class ObjWithPyCallback
{
public:
ObjWithPyCallback();
~ObjWithPyCallback();
void setCallback(Callback &callback);
void call();
private:
Callback* callback_;
};
#endif
文件ObjWithPyCallback.cpp:
#include "ObjWithPyCallback.h"
#include "Callback.h"
#include <iostream>
ObjWithPyCallback::ObjWithPyCallback() : callback_(NULL) {}
ObjWithPyCallback::~ObjWithPyCallback()
{
}
void ObjWithPyCallback::setCallback(Callback &callback)
{
callback_ = &callback;
}
void ObjWithPyCallback::call()
{
if ( ! callback_ )
{
std::cerr << "No callback is set.\n";
}
else
{
callback_->call(*this);
}
}
答案 1 :(得分:3)
我会使用SWIG的机制来处理继承,并且有一个带有虚函数void call()
的回调类。然后使用SWIG将该类从Python派生。
在Python中,您只需确保设置回调的位置,将其包装在从C ++回调类派生的Python类的实例中,并使其call
成员函数执行回调。这也是你进行测试以查看它是否可调用的地方。然后,您将使用此包装器对象调用setCallback
函数。
答案 2 :(得分:2)
class Callback{
public:
virtual void run(int n);
virtual ~Callback() {};
};
extern Callback * callback;
extern void doSomeWithCallback();
extern void setCallback(Callback * cb);
#include <iostream>
#include "example.h"
int n=0;
Callback * callback = NULL;
void Callback::run(int n){
std::cout << "This print from C++: n = " << n << std::endl;
}
void setCallback(Callback * cb){
callback = cb;
}
void doSomeWithCallback(){
if(callback == NULL){
std::cout << "Must set callback first!" << std::endl;
}else{
callback->run(n++);
}
}
/* File : example.i */
%module(directors="1") example
%{
#include "example.h"
%}
/* turn on director wrapping Callback */
%feature("director") Callback;
%include "example.h"
$ swig -c++ -python example.i
$ g++ -c -fPIC example.cxx example_wrap.cxx -I/usr/include/python2.7/
$ g++ -shared example.o example_wrap.o -o _example.so
In [1]: import example
In [2]: example.doSomeWithCallback()
Must set callback first!
In [3]: callback = example.Callback()
In [4]: example.setCallback(callback)
In [5]: example.doSomeWithCallback()
This print from C++: n = 0
In [6]: class Callback(example.Callback):
...: def run(self, n):
...: print 'This print from Python: n =', n
...:
In [7]: callback = Callback()
In [8]: example.setCallback(callback)
In [9]: example.doSomeWithCallback()
This print from Python: n = 1
我认为你还需要更多的东西。尝试:
$ ls swig-x.x.x/Examples/python