pip install pybind11
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");
}
c++ -O3 -Wall -shared -std=c++11 -fPIC \
$(python3-config --includes) \
$(python3 -m pybind11 --includes) \
-o myModule$(python3-config --extension-suffix) \
wrapper.cpp
# 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