Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Python: Getting a python weak reference to a wrapped C++ object

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?

like image 676
uli Avatar asked Dec 19 '12 15:12

uli


People also ask

What is __ Weakref __ in Python?

__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.

How do you make a weak reference in Python?

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.

What is Python weak reference?

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.

What is Weakref proxy?

weakref. proxy(object[, callback]) Return a proxy to object which uses a weak reference.


1 Answers

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.

like image 195
WaffleSouffle Avatar answered Oct 11 '22 02:10

WaffleSouffle