Seamless operability between C++11 and Python / Matlab¶
This section is for enthusiastic students who want for example connect their embedded hardware and measuremnt directly into the scientific framework of Python or Matlab.
- Python solution:
pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code.
- Matlab solution:
You can call your own C or C++ programs from the MATLAB command line as if they were built-in functions. These programs are called MEX functions and the function name is the MEX file name.
Python pybind11¶
Python modul installation
pip3 install pybind11
Micky Mouse example¶
#include <pybind11/pybind11.h>
// Linux
// c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
// MacOS
// c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
Binding to NumPy¶
The example shows an implementation of the tridiagonal solver in C/C++ with pybind11 binding to python3.
- Build:
- // Linuxc++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 - -includes) tridiagsolverNumpy.cpp -o tridiag$(python3-config - -extension-suffix)// MacOSc++ -O3 -Wall -shared -std=c++14 -undefined dynamic_lookup $(python3 -m pybind11 - -includes) tridiagsolverNumpy.cpp -o tridiag$(python3-config - -extension-suffix)// Windows
Download: tridiagsolverNumpy.cpp
- Usage:
# import numpy import numpy as np # import the new solver from tridiag module: from tridiag import solve n = 50 ad = 2*np.ones(n) al = -np.ones(n-1) au = -np.ones(n-1) b = 3*np.ones(n) solve(ad, al, au, b)
array([ 75., 147., 216., 282., 345., 405., 462., 516., 567., 615., 660., 702., 741., 777., 810., 840., 867., 891., 912., 930., 945., 957., 966., 972., 975., 975., 972., 966., 957., 945., 930., 912., 891., 867., 840., 810., 777., 741., 702., 660., 615., 567., 516., 462., 405., 345., 282., 216., 147., 75.])
Matlab MEX¶
The same example for the Matlab MEX interface. To build the code use in the matlab console:
mex tridiagsolverMEX.c
- Download: