[C++-sig] Boost.Python: Callbacks to class functions

diego_pmc paulc.mnt at gmail.com
Mon Aug 1 16:50:47 CEST 2011


I have an `EventManager` class written in C++ and exposed to Python. This is
how I intended for it to be used from the Python side:

    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`.)

The problem with the above code is that the callbacks are captured inside
`boost::python::object` instances; 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).

The code works well for functions that don't have a `self` argument (i.e.
free or static functions). How should I capture Python function objects such
that I won't increase their reference count? I only need a weak reference to
the objects.

--
View this message in context: http://boost.2283326.n4.nabble.com/Boost-Python-Callbacks-to-class-functions-tp3709880p3709880.html
Sent from the Python - c++-sig mailing list archive at Nabble.com.


More information about the Cplusplus-sig mailing list