I copied the example from the pybind11 documentation:
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function which adds two numbers");
}
Built it like so:
g++ -fPIC -shared -I/usr/include/python3.7 -o example.so example.cpp
Then:
$ python3
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from example import *
>>> add(1, 2)
3
>>> add(1.0, 2.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add(): incompatible function arguments. The following argument types are supported:
1. (arg0: int, arg1: int) -> int
Invoked with: 1.0, 2.0
>>>
I realize I could rewrite add to take double arguments and then truncate them inside the body of add. But is there a way to tell pybind11 that it's ok to to pass floats to the function (even though it takes int arguments) and have it perform the conversion automatically?
According to the docs, the opposite (conversion from integer types to double) is done implicitly and automatically.