使用 pybind11 从 c 调用 Python 函数

新手上路,请多包涵

我正在尝试从包含 main() 函数的 C++ 代码中调用 python 函数,该函数使用 Pybind11 。但我发现很少有可用的参考资料。大多数现有文档都在谈论相反的方向,即从 Python 调用 C++。

有没有完整的例子展示如何做到这一点?我找到的唯一参考是: https ://github.com/pybind/pybind11/issues/30

但它的信息很少。

原文由 stanleyli 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
1 个回答

您的问题的答案实际上有两个部分:一个是关于从 C++ 调用 Python 函数,另一个是关于嵌入解释器。

在 pybind11 中调用函数只需将该函数放入 pybind11::object 变量中,您可以在该变量上调用 operator() 来尝试调用该对象。 (它不必是函数,而只是可调用的东西:例如,它也可以是具有 __call__ 方法的对象)。例如,要从 C++ 代码中调用 math.sqrt(2) 您将使用:

 auto math = py::module::import("math");
auto resultobj = math.attr("sqrt")(2);
double result = resultobj.cast<double>();

或者您可以将其全部压缩为:

 double result = py::module::import("math").attr("sqrt")(2).cast<double>();

问题的第二部分涉及如何从 C++ 可执行文件执行此操作。在构建可执行文件时(即当您的 C++ 代码包含 main() 时),您必须先将 Python 解释器嵌入到二进制文件中,然后才能使用 Python 执行任何操作(例如调用 Python 函数)。

嵌入式支持是当前 pybind11 master 分支(将成为 2.2 版本)中添加的新功能。这是一个启动嵌入式 Python 解释器并调用 Python 函数( math.sqrt )的基本示例:

 #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";
}

输出:

 The square root of 2 is: 1.41421

有关调用函数和嵌入的更多示例和文档,请访问 http://pybind11.readthedocs.io/en/master/advanced/pycpp/object.htmlhttp://pybind11.readthedocs.io/en/master/advanced/ embedding.html ,分别。

原文由 Jason Rhinelander 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏