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):
clair-c2py struct1.cpp -- -std=c++20 `c2py_flags -i`
clang++ 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