pybind11 调用 python

创建日期: 2023-01-07 20:33 | 作者: 风波 | 浏览次数: 20 | 分类: C++

1. 下载 pybind11、安装 python38-devel

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
20 浏览
15 爬虫
0 评论