I've wrapped a C++ class using Boost.Python. These Objects have strong references (boost::shared_ptr) on the C++-side, and there may be intermittent strong references in Python as well. So far, everything works well. However, if I create a python weak reference from one of the strong references, this weak reference is deleted as soon as the last python strong reference disappears. I'd like the weak reference to stay alive until the last strong reference on the C++ side disappears as well. Is it possible to achieve that?
Phrased another way: Is there a way to find out from python if a particular C++ object (wrapped by Boost.Python) still exists?
__weakref__ is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref (or sometimes weakproxy ) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.
To create weak references in python, we need to use the weakref module. The weakref is not sufficient to keep the object alive. A basic use of the weak reference is to implement cache or mappings for a large object. Not all objects can be weakly referenced.
Python contains the weakref module that creates a weak reference to an object. If there are no strong references to an object, the garbage collector is free to use the memory for other purposes. Weak references are used to implement caches and mappings that contain massive data.
weakref. proxy(object[, callback]) Return a proxy to object which uses a weak reference.
How are you holding a "C++ strong reference" to the wrapped class ?
I'm quite rusty on boost python, but I believe it's the boost::shared_ptr's deleter presence which ensures lifetime management.
If that isn't the problem, you probably need to hold the instance in C++ in a boost::python::object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With