Sitemap

Using Python with C++. Part2.

3 min readMar 6, 2023

--

Using Python and C++ together using Pybind library.

In the previous episode…

In the first part i made an example on how to call from a python script a C++ function, this time let’s go further and explore more advanced use cases.

Summary

We are going to implement a C++ class and make it visible to python. Here we will be able to access to member functions, operators and variables.

A simple struct

Suppose to have a simple struct Guitar:

struct Guitar
{
Guitar(const std::string& manufacturer_name, const float price,
const int num_strings)
: mManufacturerName(manufacturer_name)
, mPrice(price)
, mNumStrings(num_strings)
{}

Guitar(const std::string& manufacturer_name, const float price)
: mManufacturerName(manufacturer_name)
, mPrice(price)
{}

Guitar() {}

void SetManufacturer(const std::string& manufacturer_name)
{
mManufacturerName = manufacturer_name;
}

void SetPrice(const float price)
{
mPrice = price;
}

float mPrice {0.f};
int mNumStrings {0};
std::string mManufacturerName {""};
};

Inside the PYBIND11_MODULE macro we create the binding using :

PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example";

py::class_<Guitar>(m, "Guitar")
.def(py::init<const std::string&, const float, const int>())
.def(py::init<const std::string&, const float>())
.def(py::init<>())
.def("set_manufacturer", &Guitar::SetManufacturer)
.def("set_price", &Guitar::SetPrice)
.def_readwrite("num_strings", &Guitar::mNumStrings)
.def_readonly("manufacturer", &Guitar::mManufacturerName)
.def_readonly("price", &Guitar::mPrice);
}
  • py::class_<CLASS_NAME> which creates a binding of the whole C++ class or struct.
  • The command .def(py::init<…..>()) binds the constructor of Guitar with a convenience function py::init which wraps the constructor by taking the types of constructor’s parameters as template arguments.
  • In this example we have three constructors, consequently i have called the command .def three times, every time with different template arguments according to constructors’ definitions.
  • To bind a member variable we can use two options: def_readwrite or def_readonly. The first one will make the variable accessible both in reading and writing, the second one only in reading. If you are going to set that variable, python will throw an error.

The example in Python will make things clearer:

  • Here we have 3 instances of Guitar, guitar1, guitar2, guitar3, every one created with a different Constructor. I can use two methods set_manufacturer and set_price. I can set directly num_strings variable which is defined as readwrite but not price which is defined as readonly.
from example import Guitar

guitar1 = Guitar("Fender", 1500.0, 6)

guitar2 = Guitar("Ibanez", 800.0)
guitar2.num_strings = 7

guitar3 = Guitar()

guitar3.set_manufacturer("Gibson")
guitar3.set_price(2400.0)
guitar3.num_strings = 6

guitar3.price = 100.0 # error !
Press enter or click to view image in full size
Let’s have a break for one moment before going to the next example. A wonderful scene from The Office (one of the my most favourite tv series) ep 14 season 5, Stress Relief. People learn in lots of different ways, but the experience is the best teacher. Is this also true in programming? :)

A templated class

Ok, let’s restart after a short break. Let’s take another example a templated class Container which is basically a wrapper of a dynamically allocated data array of type T.

template <typename T>
class Container
{
public:
Container(const size_t num_elements)
{
mData = std::make_unique<T[]>(num_elements);
}

T& operator [](const size_t index)
{
return mData[index];
}

const T& operator [](const size_t index) const
{
return mData[index];
}

private:
std::unique_ptr<T[]> mData;
};

Again here we use the PYBIND11_MODULE macro to create bindings:

  • With py::class_<Container<double>> i create a binding of the specialized templated class Container<double>
  • I have also defined two lambda functions (needed in this case to manage the operator overloading [ ]). This because, in python, you can use special methods __setitem__(self, index, value) and __getitem__(self, index) to work with array index operator [].
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example";

py::class_<Container<double>>(m, "Container")
.def(py::init<const size_t>())
.def("__getitem__", [](const Container<double>&cont, size_t index){
return cont[index];
})
.def("__setitem__", [](Container<double>&cont, size_t index, double value){
cont[index] = value;
});
}

Note: C++ templates may only be instantiated at compile time, so pybind11 can only wrap instantiated templated classes. You cannot wrap a non-instantiated template:

PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example";

py::class_<Container>(m, "Container")
.def(py::init<const size_t>());
}

This last case will throw an error.

Get Stefano C’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s see how i will use this class in python:

from example import Container

container = Container(10)

for i in range(0, 10):
container[i] = i

for i in range(0, 10):
print(container[i])

0.0
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0

Very simple. Is it n’t ?

  • As you can see, you can import the class Container from the module example, then instantiate the class passing the number of elements and then you can set / get the item at index i through the operator [].

If you have some troubles in building the library, please, give a look to the first part where i show how to build the library with cmake.

That’s all for now. Next time we will see other interesting examples.

So, if you like this content, please consider to follow me on Medium :) Happy reading, Stefano.

--

--

Stefano C
Stefano C

Written by Stefano C

Master Degree in Physics, work in audio industry. Passion for C++, python, audio, robotics, electronics and programming. Modena, italy.