py使用pybind11调用c++示例.

#include <pybind11/pybind11.h>
namespace py = pybind11;

int add(int i, int j){
return i + j;
}

PYBIND11_MODULE(aa, m){//用宏,这里为aa,就是模块
//m.doc() = "pybind11 example plugin";
// expose add function, and add keyword arguments and default arguments
m.def("add",&add,"加法",py::arg("i")=1,py::arg("j")=2);
//导出变量
m.attr("the_answer") = 42;
py::object world = py::cast("World");
m.attr("what") = world;
}

编译命令:

cl a.cpp /LD /Fe:aa.pyd

使用:

import aa
b=aa.add(3, 4)
print(b)