Functions

Default Behavior & Customization

  1. Every function defined in the C++ source files is wrapped, subject to the customization options (see options).

  2. Only functions whose arguments and return types are convertible types (see the list of convertible types) can be wrapped.

  3. If a function cannot be wrapped because its argument or return type is not convertible, clair-c2py will generate a Clang compile-time error with a diagnostic. For example, the following C++ code:

    fail.cpp
    #include <c2py/c2py.hpp>
    
    double *make_raw_pointer(long size) { return new double[size]; }
    
    void f(FILE *x) {}
    

    will trigger the following compilation error:

    fail.cpp:3:1: error: c2py: Cannot convert a raw C++ pointer to Python
    3 | double *make_raw_pointer(long size) { return new double[size]; }
       | ^
    fail.cpp:5:8: error: c2py: Cannot convert this argument from Python to C++
    5 | void f(FILE *x) {}
       |        ^
    

To fix such errors, you can exclude the problematic function using the customization options (see Customization).

Template Functions

For generic (template) functions, clair-c2py only generates bindings for their explicit instantiations, subject to the same customization rules as regular functions.

In the following example, we define a function template add that adds two values of the same type and explicitly instantiate it for three simple types. Dynamic dispatch in Python works exactly as it does for regular functions.

function_template.cpp
#include "c2py/c2py.hpp"
#include <string>

template <typename T> T add(T a, T b) { return a + b; }

// clair-c2py will generate bindings for these EXPLICIT instantiations.
template int add(int a, int b);
template double add(double a, double b);
template std::string add(std::string a, std::string b);
>>> from function_template import add
>>> add(1, 2)
3
>>> add(2.0, 5.0)
7.0
>>> add("Hello, ", "world!")
'Hello, world!'
>>> add(1, 2.0)
3.0

Coroutines, generators

  • Coroutines are supported and can be wrapped, including generators.

    (Example to be added.)