C2PY_WRAP_AS_METHOD

The C2PY_WRAP_AS_METHOD annotation lets us add a function as a method to the first argument’s class object.

C++ code

// c2py_wrap_as_method.cpp

#include "c2py/c2py.hpp"

// Some class we want to wrap.
struct myclass {
  int x{};
};

// We want to add this function as a method to myclass in the Python bindings.
C2PY_WRAP_AS_METHOD int f(const myclass &m, int y) { return m.x * y; }

Usage in Python

After generating the extension module, we can use it in Python:

>>> from c2py_wrap_as_method import *
>>> m = Myclass(x = 100)
>>> m.f(5)
500
>>> f(5)
Traceback (most recent call last):
File "<python-input-5>", line 1, in <module>
    f(5)
    ^
NameError: name 'f' is not defined

The free C++ function f has been added as a method to the Myclass class in Python.