Skip to content

Redesign Python-callback mechanism for explicit memory management (Major change)

Ammar Nejati requested to merge a.cleanUpSWIG_PyCallbacks into main

Generating an ISimulation instance via calling a Python function and the corresponding memory management has become explicit in the new implementation.

The previous mechanism was based on the (black-box) SWIG special functionality __disown__ which instructs the Python interpeter to leave memory management of a Python object to the underlying C++ library.

Note that a Python callable which produces an ISimulation instance (wrapped in a Python object) must be carefully managed so that the memory allocated for the ISimulation instance as well as that of its Python-wrapper be released after simulation is done.

The new mechanism is introduced in the SWIG header libBornAgainSim.i. It makes Python calling mechanism and memory management of Python objects explicit, and hides all the details of Python call and garbage collection form the C++ core.

The previous mechanism of PyFittingCallbacks is completely removed from the BornAgain Sim module and a new class SimulationWrapper is introduced which encapsulates a C++/Python simulation takes care of memory management for C++/Python calls. The Python call and garbage collection mechanism is strictly left to the SWIG API part; i.e., no 'information leak' to C++ core.

A similar mechanism is implemented in libBornAgainSim.i for FitObjective::initPlot method which can accept a Python callable to plot a FitObjective instance.

The methods FitObjective::addFitPair and FitObjective::initPlot are rewritten to adapt to the new mechanism.

The unneeded classes PyBuilderCallback and PyObserverCallback are removed. There is no need for SWIG 'shared-pointer' and 'director' functionality anymore. So, the SWIG-produced API simplifies considerably.

Furthermore, the SWIG headers and tweak.py are cleaned up.

Related to #127 (closed)

Merge request reports

Loading