Examples

Functions

The following example shows a C++ function that takes a std::vector<double> and returns the sum of its elements:

// fun2.cpp

#include <c2py/c2py.hpp>
#include <vector>
#include <numeric>

double sum(std::vector<double> const &v) { return std::accumulate(begin(v), end(v), 0.0); }

We can then generate the Python bindings for this function and compile them with (assuming OS X and clang):

$ clang++ -fplugin=clair_c2py.dylib  fun2.cpp -std=c++20 -shared -o fun2.so `c2py_flags`

Finally, we use the module in Python:

>>> import fun2 as M
>>> M.sum([1.2, 2.3, 4.5])
8.0

Classes

The following example shows a simple C++ struct and how to make it printable in Python:

// struct1.cpp

#include <c2py/c2py.hpp>

struct S {
  int i;

  S(int i) : i{i} {}

  int m() const { return i + 2; }
};

// A function using S
int f(S const &s) { return s.i; }

// make S printable in C++
std::ostream &operator<<(std::ostream &out, S const &s) { return out << "S struct with i=" << s.i << '\n'; }

We can again generate the Python bindings for this function and compile them with (assuming OS X and clang):

$ clang++ -fplugin=clair_c2py.dylib  struct1.cpp -std=c++20 -shared -o struct1.so `c2py_flags`

Finally, we use the module in Python:

>>> import struct1 as M
>>> s = M.S(2)
>>> s.i
2
>>> s.m()
2
>>> print(s)
S struct with i=2
>>> M.f(s)
2