Skip to content

Instantly share code, notes, and snippets.

@jmftrindade
Last active July 13, 2023 21:43
Show Gist options
  • Save jmftrindade/08b76aa2013ecaec4a726aa1e14965cc to your computer and use it in GitHub Desktop.
Save jmftrindade/08b76aa2013ecaec4a726aa1e14965cc to your computer and use it in GitHub Desktop.

PyBind11 example

1) Deps

pip install pybind11

2) Python wrapper

Original C++ code:

// inertia.cpp
#include <cmath>
#include <vector>

double calculate_moment_of_inertia(const std::vector<double> &m,
                                   const std::vector<double> &r) {
  if (m.size() != r.size()) {
    throw std::invalid_argument(
        "The size of the mass and radius vectors must be the same");
  }

  double inertia = 0.0;
  for (size_t i = 0; i < m.size(); i++) {
    inertia += m[i] * std::pow(r[i], 2);
  }

  return inertia;
}

A possible wrapper for it:

// wrapper.cpp
#include <cmath>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>

double calculate_moment_of_inertia(const std::vector<double> &m,
                                   const std::vector<double> &r) {
  if (m.size() != r.size()) {
    throw std::invalid_argument(
        "The size of the mass and radius vectors must be the same");
  }

  double inertia = 0.0;
  for (size_t i = 0; i < m.size(); i++) {
    inertia += m[i] * std::pow(r[i], 2);
  }

  return inertia;
}

PYBIND11_MODULE(myModule, m) {
  m.def("calculate_moment_of_inertia", &calculate_moment_of_inertia,
        "A function which calculates the moment of inertia");
}

3) Compile wrapper

c++ -O3 -Wall -shared -std=c++11 -fPIC \
  $(python3-config --includes) \
  $(python3 -m pybind11 --includes) \
  -o myModule$(python3-config --extension-suffix) \
  wrapper.cpp

4) Call it from python

# main.py
import myModule

masses = [1.0, 2.0, 3.0]
distances = [1.0, 2.0, 3.0]
inertia = myModule.calculate_moment_of_inertia(masses, distances)
print(inertia)
$ python3 main.py
36.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment