1. 代码
#c++部分
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
#bingding部分
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function that adds two numbers");
}
以上构建后可以通过使用help(example)可以查看使用方法
2. 如果需要指定add的参数,需要如下
m.def("add", &add, "A function which adds two numbers",
py::arg("i"), py::arg("j"));
3. 如果需要默认的参数
m.def("add", &add, "A function which adds two numbers",
py::arg("i") = 1, py::arg("j") = 2);
4. 类型明确的转换
以下将在example域内,定义了参数the_answer = 42, what=“Word”.
如:
import example >>> example.the_answer 42 >>> example.what 'World'
PYBIND11_MODULE(example, m) {
m.attr("the_answer") = 42;
py::object world = py::cast("World");
m.attr("what") = world;
}