We will keep account.cpp unchanged with respect to the previous two recipes and only modify account.hpp:
#pragma once
#include <pybind11/pybind11.h>
class Account {
public:
Account();
~Account();
void deposit(const double amount);
void withdraw(const double amount);
double get_balance() const;
private:
double balance;
};
namespace py = pybind11;
PYBIND11_MODULE(account, m) {
py::class_<Account>(m, "Account")
.def(py::init())
.def("deposit", &Account::deposit)
.def("withdraw", &Account::withdraw)
.def("get_balance", &Account::get_balance);
}
We will follow the pybind11 documentation "Building with CMake" (https://pybind11.readthedocs.io/en/stable/compiling.html#building-with-cmake) and introduce the pybind11 CMake code using add_subdirectory. However, we will not place the pybind11 source code explicitly into our project directory, but rather demonstrate how to fetch pybind11 sources at configure time using FetchContent (https://cmake.org/cmake/help/v3.11/module/FetchContent.html).
For better code reuse in the next recipe, we will also place all sources into a subdirectory and use the following project layout:
.
├── account
│ ├── account.cpp
│ ├── account.hpp
│ ├── CMakeLists.txt
│ └── test.py
└── CMakeLists.txt