在 python 邮件列表上得到了答案,经过一些修改和更多的研究,我得到了我想要的 :)
我确实在 mithrandi 之前看过那篇文章,但我不喜欢必须像这样声明函数的想法。使用一些花哨的包装器和一点 python 魔法,它可以同时工作并且看起来很好!
首先,用这样的代码包装你的 python 对象
struct timer_func_wrapper_t
{
timer_func_wrapper_t( bp::object callable ) : _callable( callable ) {}
bool operator()()
{
// These GIL calls make it thread safe, may or may not be needed depending on your use case
PyGILState_STATE gstate = PyGILState_Ensure();
bool ret = _callable();
PyGILState_Release( gstate );
return ret;
}
bp::object _callable;
};
boost::int32_t createTimerWrapper( Class* class, boost::uint64_t interval, bp::object function, bool recurring = false )
{
return class->createTimer( interval, boost::function<bool ()>( timer_func_wrapper_t( function ) ), recurring );
}
当在你的类中定义这样的方法
.def( "createTimer", &createTimerWrapper, ( bp::arg( "interval" ), bp::arg( "function" ), bp::arg( "recurring" ) = false ) )
有了一点点包装,你就可以像这样施展魔法
import MyLib
import time
def callMePls():
print( "Hello world" )
return True
class = MyLib.Class()
class.createTimer( 3, callMePls )
time.sleep( 1 )
为了完全模仿 C++,我们还需要一个 boost::bind 实现,可以在这里找到:http ://code.activestate.com/recipes/440557/
有了这个,我们现在可以做这样的事情
import MyLib
import time
def callMePls( str ):
print( "Hello", str )
return True
class = MyLib.Class()
class.createTimer( 3, bind( callMePls, "world" ) )
time.sleep( 1 )
编辑:
我喜欢尽可能跟进我的问题。我成功地使用了这段代码一段时间,但我发现当你想在对象构造函数中使用 boost::function 时,它会崩溃。有一种方法可以使它与此类似,但是您构造的新对象最终会具有不同的签名,并且不能与像它自己一样的其他对象一起使用。
这最终让我感到厌烦,不得不对此做点什么,因为我对 boost::python 有了更多的了解,现在我想出了一个使用转换器的非常好的“适合所有人”的解决方案。此处的代码会将可调用的 python 转换为 boost::python< bool() > 对象,可以轻松修改它以转换为其他 boost 函数。
// Wrapper for timer function parameter
struct timer_func_wrapper_t
{
timer_func_wrapper_t( bp::object callable ) : _callable(callable) {}
bool operator()()
{
return _callable();
}
bp::object _callable;
};
struct BoostFunc_from_Python_Callable
{
BoostFunc_from_Python_Callable()
{
bp::converter::registry::push_back( &convertible, &construct, bp::type_id< boost::function< bool() > >() );
}
static void* convertible( PyObject* obj_ptr )
{
if( !PyCallable_Check( obj_ptr ) ) return 0;
return obj_ptr;
}
static void construct( PyObject* obj_ptr, bp::converter::rvalue_from_python_stage1_data* data )
{
bp::object callable( bp::handle<>( bp::borrowed( obj_ptr ) ) );
void* storage = ( ( bp::converter::rvalue_from_python_storage< boost::function< bool() > >* ) data )->storage.bytes;
new (storage)boost::function< bool() >( timer_func_wrapper_t( callable ) );
data->convertible = storage;
}
};
然后在您的初始化代码中,即 BOOST_PYTHON_MODULE(),只需通过创建结构来注册类型
BOOST_PYTHON_MODULE(Foo)
{
// Register function converter
BoostFunc_from_Python_Callable();