2

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.

4
  • You'll probably want to look into the weakref (docs.python.org/2/library/weakref.html) module Commented Jul 18, 2013 at 20:01
  • @Brien: Hmm... not sure weakref would not help in this case. The C code itself is failing to do a Py_DECREF - a weakref would only allow me not to increase the reference count any more than it is. Although, I suppose I could go looking for a reference to the object I already own and turn it into a weakref... hmm... Commented Jul 18, 2013 at 20:04
  • 2
    You could try to use the Python C API Py_DecRef via ctypes. See github.com/matplotlib/matplotlib/commit/… for an example that works around a memory leak in PySide. Commented Jul 18, 2013 at 20:08
  • @Claudiu My mistake. When I read your question thought the C library was a separate example and you were trying to implement a similar functionality in pure Python. Commented Jul 18, 2013 at 20:11

1 Answer 1

11

Use Py_DecRef via ctypes:

import ctypes

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

_decref(a_python_object)
Sign up to request clarification or add additional context in comments.

1 Comment

just what i'm looking for - thanks! Also appreciated the PySide link to see how someone else did it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.