从c++程序调用python进行分发

2024-06-02 05:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Boost有一个python接口库,可以帮助您。

Boost.Python

I would like to call python script files from my c++ program.

这意味着你要在你的C++应用程序中嵌入Python。如Embedding Python in Another Application所述:

Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code.

我建议你先通过Embedding Python in Another Application。然后参考以下示例

  1. Embedding Python in C/C++: Part I

  2. Embedding Python in C/C++: Part II

  3. Embedding Python in Multi-Threaded C/C++ Applications

如果您喜欢Boost.Python,可以访问以下链接:

  1. Embedding Python with Boost.Python Part 1

有趣的是,还没有人提到pybind11。从他们的文件来看:

pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code. Its goals and syntax are similar to the excellent Boost.Python library by David Abrahams: to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection. [...] Since its creation, this library has grown beyond Boost.Python in many ways, leading to dramatically simpler binding code in many common situations.

具体来说,调用Python函数(称为嵌入)非常简单(取自documentation):

#include <pybind11/embed.h> // everything needed for embedding
namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{}; // start the interpreter and keep it alive
    py::print("Hello, World!"); // use the Python API
}

相关问题 更多 >