1

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)

isuruf
  • 2,323
  • 12
  • 14
  • I don't think so. As far as I understand, Python's GC will one deals with object it allocated himself. So it won't deals with C++ reference. – hivert Jul 09 '17 at 07:15
  • 1
    There are [very hacky ways](https://groups.google.com/forum/#!topic/cython-users/OW3z9HsxlNI) of overriding `tp_traverse` to help it identify the reference cycle. – DavidW Jul 09 '17 at 12:03

0 Answers0