0%

Pybind11

1. What

  • Header only library
  • Expose C++ function, classes and objects as Python module

2. How to Use

  1. Include the pybind11
  2. define python modules using macros
  3. export to python module

3. Example

my_class.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once

#include <string>

class MyClass {
public:
MyClass(const std::string& name);
void setName(const std::string& name);
std::string getName() const;

private:
std::string name_;
};

my_class.cpp

1
2
3
4
5
6
7
8
9
10
11
#include "my_class.h"

MyClass::MyClass(const std::string& name) : name_(name) {}

void MyClass::setName(const std::string& name) {
name_ = name;
}

std::string MyClass::getName() const {
return name_;
}

My_module.cpp

1
2
3
4
5
6
7
8
9
10
11
#include <pybind11/pybind11.h>
#include "my_class.h"

namespace py = pybind11;

PYBIND11_MODULE(my_module, m) {
py::class_<MyClass>(m, "MyClass")
.def(py::init<const std::string&>())
.def("setName", &MyClass::setName)
.def("getName", &MyClass::getName);
}

In python

1
2
3
4
5
6
import my_module

obj = my_module.MyClass("Hello, world!")
print(obj.getName()) # prints "Hello, world!"
obj.setName("Goodbye, world!")
print(obj.getName()) # prints "Goodbye, world!"

4. Datatype?

Pybind11 auto perform type conversions