Question

I have a C extension module for Python.

When the module is initialized, I malloc() some memory that I only use in the C code.

I would like to free this memory when the module is freed.

Python 3 has m_free member on PyModuleDef struct that is exactly what I want. The problem is I cannot find equivalent functionality in Python 2.

How do I free my malloc'd memory in Python 2?

Was it helpful?

Solution

I suppose there is no direct equivalent, that's why m_free is introduced in 3.0, see pep 3121 for details:

Currently, extension modules are initialized usually once and then "live" forever. The only exception is when Py_Finalize() is called: then the initialization routine is invoked a second time. This is bad from a resource management point of view: memory and other resources might get allocated each time initialization is called, but there is no way to reclaim them. As a result, there is currently no way to completely release all resources Python has allocated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top