I have a Cython extension class that keeps a shared pointer to a C++ class. The class itself keeps a pointer to the Cython class.
cdef class A
cdef shared_ptr[B] thisptr
def __init__(Basic self, name, *args, **kwargs):
self.thisptr = create_b(<PyObject*>self)
I need the python object to stay alive while thisptr is alive and thisptr to stay alive while the python object is alive. (C++ class B is designed so that it will increase the refcount of the python object it is storing when it is created and refcount is decreased once the C++ object is destroyed.) Note that thisptr maybe shared by other Python objects, but this class is the one creating the object.
This situation leads to a cyclic reference.
Is there a way to indicate to the python garbage collector to consider this a cyclic reference and free the python object if there is only one reference to it? (i.e. from the C++ object)