Finalizing C extension modules

Martin v. Löwis loewis at informatik.hu-berlin.de
Thu Apr 18 12:09:48 EDT 2002


Matthias Baas <baas at ira.uka.de> writes:

> Suppose I have a C/C++ module that allocates some resources in its
> init function, where would be the proper place to release them again
> when the Python interpreter is shutting down? Is there an equivalent
> to Py_Finalize() for extension modules? 

You can use Py_AtExit.

> Why is it that extension modules aren't unloaded?

There is no portable, platform-independent way to provide that
feature; platforms have strange restrictions for unloading of shared
libraries. Furthermore, it might lead to surprising crashes: Somebody
may still hold a reference into some piece of code of the module; if
the module has been unloaded, calling the function at the C level will
just crash.

> However, I will never call Py_DECREF() for that class object I was
> retrieving from the pure Python module. Is this ok? Or will this
> result in a memory leak? Where am I supposed to call Py_DECREF()?

This will result in a memory leak, but that is no problem: Once the
operating system process terminates, the operating system will reclaim
all memory of the process, and most other resources.

If you are worried that you should release the object, register a
function with Py_AtExit.

HTH,
Martin




More information about the Python-list mailing list