【发布时间】:2020-12-11 00:52:07
【问题描述】:
我从 pybind11 文档中复制了示例:
#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");
}
这样构建:
g++ -fPIC -shared -I/usr/include/python3.7 -o example.so example.cpp
然后:
$ 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
>>>
我意识到我可以重写add 以获取double 参数,然后在add 的主体内截断它们。但是有没有办法告诉 pybind11 可以将浮点数传递给函数(即使它需要 int 参数)并让它自动执行转换?
根据文档,相反(从整数类型转换为double)是隐式自动完成的。
【问题讨论】:
标签: python c++ python-3.x pybind11