Python C API: How to debug reference leak?

dieter dieter at handshake.de
Wed Sep 28 03:02:07 EDT 2016


dl l <ldlchina at gmail.com> writes:

> Thanks for reply. Is there any function in C to get the reference objects
> of a object? I want to debug where are referencing the object.

Depending on your understanding of "reference objects", this would
be "gc.get_referents" or "gc.get_referrers".

Of course, those are not "C" functions but Python functions in the module
"gc". However, (with some effort) you can use them in "C" as
well.

Most types (at least the standard container types) will have
"gc" support functions which allow to determine the "referents"
of a corresponding object.

Note: those "gc" functions are implemented in "C". But, almost surely,
they are declared "static", i.e. not globally exposed (in order
not to pollute the global symbol namespace).


When I want to use Python functions in C, I write a bit of "Cython" source
and use "Cython" to compile it into "C". Then, I copy and paste
this "C" code into my own "C" application to have the functions
available there.


Important note for debugging:
(Almost) all Python functions expect that they are called only when the
active thread holds the GIL ("Global Interpreter Lock").
Calling Python functions during debugging may violate this restriction
and this can lead to abnormal behaviour.

In single thread applications, the real danger is likely not too large.
In multi thread applications, I have already seen "SIGSEGV"s caused
by this.




More information about the Python-list mailing list