Gyoto
Public Member Functions | Private Attributes | List of all members
Gyoto::Python::GILGuard Class Reference

Manage the GIL and free pointers on error. More...

#include <GyotoPython.h>

Public Member Functions

 GILGuard ()
 Constructor: Acquires the GIL.
 
 ~GILGuard ()
 Destructor. More...
 
void track (PyObject *&obj)
 Add a PyObject* to the list of tracked objects.
 
 GILGuard (const GILGuard &)=delete
 
GILGuardoperator= (const GILGuard &)=delete
 

Private Attributes

PyGILState_STATE gstate_
 The GIL state guarded by this GILGuard.
 
std::vector< PyObject ** > tracked_objects_
 Stores pointers to PyObject* variables.
 

Detailed Description

Manage the GIL and free pointers on error.

Any function that makes calls to the Python C API must acquire the Python Global interpreter lock (GIL) before the first call and release it before returning. It can be difficult and error-prone to answer that the GIL is always released, enspecially in C++ code that can throw error. Additionally, there is often a need to dereference pointers to temporary PyObject variables.

This class provides a convenience to simplify this task. GIL management can be implemented with is a single line before the first Python C API call:

[[maybe_unused]] Gyoto::Python::GILGuard guardian;

The GIL is acquired in the constructor of the guardian object and released in its destructor which is automatically called when the function returns or when an Error is thrown, even from a nested function.

Additionally, an arbitrary number of PyObject* pointers can be tracked with:

guardian.track(some_pointer);

Upon destruction of guardian, somepointer's reference counter will be decremented using Py_XDECREF, and somepointer will be set to zero.

Constructor & Destructor Documentation

◆ ~GILGuard()

Gyoto::Python::GILGuard::~GILGuard ( )

Destructor.

Releases the GIL and decrements all tracked PyObject* pointers.


The documentation for this class was generated from the following file: