1. 下载 pybind11、安装 python38-devel
- https://github.com/pybind/pybind11
- https://github.com/pybind/pybind11.git
yum install -y python38-devel
yum install -y boost
pip3 install pytest -i https://pypi.douban.com/simple/ --trusted-host pypi.douban.com
2. 调用 python
c++ 代码(https://stackoverflow.com/questions/42521830/call-a-python-function-from-c-using-pybind11)
#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
int main() {
py::scoped_interpreter python;
auto math = py::module::import("math");
double root_two = math.attr("sqrt")(2.0).cast<double>();
std::cout << "The square root of 2 is: " << root_two << "\n";
}
编译
g++ -g -o main main.cpp -Wall -I./ -I ../../pybind11/include/ -I /usr/include/python3.8/ -lpython3.8
运行结果
The square root of 2 is: 1.41421