Question

I'm using a C library that has a few memory issues. I've identified that sometimes it decreases the reference count too early, leading to segfaults, and managed to work around that by keeping a list of objects to inflate the reference count. On the other hand, I've also identified specific cases where the reference count is too high. Is there any way to work around these cases, from Python code, by purposefully decreasing the reference count?

I understand this is hackish and in no way clean code or anything, but I've got to deal with the buggy C library somehow, and it seems this might be easier than figuring out where the issue in the C code is (luckily it's open-source), fixing it, then recompiling it on all the platforms I have to support.

Was it helpful?

Solution

Use Py_DecRef via ctypes:

import ctypes

_decref = ctypes.pythonapi.Py_DecRef
_decref.argtypes = [ctypes.py_object]
_decref.restype = None

_decref(a_python_object)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top