[英]Boost.Python: Callbacks to class functions
I have an EventManager
class written in C++ and exposed to Python. 我有一个用C ++编写并暴露给Python的EventManager
类。 This is how I intended for it to be used from the Python side: 这就是我打算从Python端使用它的方式:
class Something:
def __init__(self):
EventManager.addEventHandler(FooEvent, self.onFooEvent)
def __del__(self):
EventManager.removeEventHandler(FooEvent, self.onFooEvent)
def onFooEvent(self, event):
pass
(The add-
and remove-
are exposed as static functions of EventManager
.) (该add-
和remove-
被暴露为静态函数EventManager
。)
The problem with the above code is that the callbacks are captured inside boost::python::object
instances; 上面代码的问题是回调是在boost::python::object
实例中捕获的; when I do self.onFooEvent
these will increase the reference count of self
, which will prevent it from being deleted, so the destructor never gets called, so the event handlers never get removed (except at the end of the application). 当我执行self.onFooEvent
这些将增加self
的引用计数,这将阻止它被删除,因此析构函数永远不会被调用,因此事件处理程序永远不会被删除(除非在应用程序结束时)。
The code works well for functions that don't have a self
argument (ie free or static functions). 该代码适用于没有self
参数的函数(即自由或静态函数)。 How should I capture Python function objects such that I won't increase their reference count? 我应该如何捕获Python函数对象,以便我不会增加它们的引用计数? I only need a weak reference to the objects. 我只需要对对象的弱引用。
Without weakref.ref(self.onFooEvent) you will never get your expected behaviour! 没有weakref.ref(self.onFooEvent)你永远不会得到你预期的行为! See my comment. 看我的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.