ExampleΒΆ
Next we present a minimal working example of PyBindCpp usage. Consider the following C++ code which includes variables and functions that we wish to export to Python:
#include <cmath>
constexpr double half = 0.5;
constexpr double pi = M_PI;
int f(int N, int n, int x) { return N + n + x; }
double mycos(double x) { return cos(x); }
To port the above code, we merely need to write a single function before compiling into a shared library that can be directly imported from Python. We must define a function which takes as its input a reference to an module
object, and uses that to register the entities that need to exported. We can use the add
attribute to register both simple types and functions. At the end we must add the PYBINDCPP_INIT
preprocessor macro which takes two arguments - the name of the module that we are creating and the name of initialization function that we just defined. This is necessary in order for Python to find the correct entry point when loading the extension module.
#include <pybindcpp/module.h>
using namespace pybindcpp;
void init(module m)
{
// numbers
m.add("half", half);
m.add("pi", pi);
m.add("one", static_cast<int>(1));
m.add("two", static_cast<unsigned long>(2));
// boolean
m.add("true", true);
m.add("false", false);
// string
m.add("name", "pybindcpp");
// functions
m.add("f", f);
m.add("mycos", mycos);
m.add("cos", [](double x) -> double { return cos(x); });
m.add("sin", static_cast<double (*)(double)>(sin));
}
PYBINDCPP_INIT(example, init)
After compiling the code above into a shared module, we can use the script below to import it from Python and run some tests to ensure that everything works as expected.
from math import cos, sin
import pybindcpp.ext.example as m
def test_example():
# numbers
assert round(m.pi, 2) == 3.14
assert m.half == 0.5
assert m.one == 1
# boolean
assert m.true is True
assert m.false is False
# string
assert m.name == b'pybindcpp'
# functions
assert m.f(1, 2, 3) == 1 + 2 + 3
assert m.mycos(0.1) == cos(0.1)
assert m.cos(0.1) == cos(0.1)
assert m.sin(0.1) == sin(0.1)
if __name__ == '__main__':
test_example()