01 pybind11 库
pybind11 只需包含头文件,即可完成python与c++的相互调用。对编译要求较高。
pybind11\include\pybind11\detail\common.h
line60 error pybind11 requires Xcode/clang 5.0 or newer
line64 error pybind11 requires gcc 4.8 or newer
line70 error pybind11 requires MSVC 2015 update 3 or newer
github:https://github.com/pybind/pybind11
官网文档:http://pybind11.readthedocs.io/en/master/
最简单的example,保存在 https://github.com/5455945/cpp_demo
test03.py 调用 test01.cpp中的add方法。
test02.cpp调用 test04.py 中的add方法。
test01.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(test01, m) {
m.doc() = "pybind11 test01 plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
test03.py
import test01
print("test01.add(3, 4) = ", test01.add(3, 4))
print("test01.add(8, 9) = ", test01.add(8,9))
test02.cpp
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
int main() {
py::scoped_interpreter python;
py::module sys = py::module::import("sys");
py::print(sys.attr("path"));
py::module t = py::module::import("test04");
t.attr("add")(1, 2);
return 0;
}
test04.py
"""test04.py located in the working directory"""
def add(i, j):
print("hello,pybind11")
return i + j
使用cmake-gui设置 python的头文件路径和lib库路径。即可。需要vs2015update3+。
运行结果