21.1 Defining a library

First consider LibUtilities. An abbreviated version of the base file, LibUtilities.cpp has the following structure:


Listing 21.1: Defining a library with pybind11
1#include <LibUtilities/Python/NekPyConfig.hpp> 
2 
3void export_Basis(py::module &); 
4void export_SessionReader(py::module &); 
5 
6// Define the LibUtilities module within the pybind11 module m‘. 
7PYBIND11_MODULE(_LibUtilities, m) 
8{ 
9    // Export classes. 
10    export_Basis(m); 
11    export_SessionReader(m); 
12}

The PYBIND11_MODULE(name, m) macro allows us to define a Python module inside C++. Note that in this case, the leading underscore in the name (i.e. _LibUtilities) is deliberate. To define the contents of the module, we call a number of functions that are prefixed by export_, which will define one or more Python classes that live in this module. These Python classes correspond with our Nektar++ classes. We adopt this approach simply so that we can split up the different classes into different files, because it is not possible to call PYBIND11_MODULE more than once.

These functions are defined in appropriately named files, for example export_Basis() lives in the file LibUtilities/Python/Foundations/Basis.cpp. This corresponds to the Nektar++ file LibUtilities/Foundations/Basis.cpp and the classes defined therein.