当前位置:首页> 正文

从 c 程序调用 python 进行分发

从 c 程序调用 python 进行分发

Calling python from a c++ program for distribution

我想从我的 c 程序中调用 python 脚本文件。

我不确定我将分发给的人是否会安装 python。

基本上,我正在寻找一个我可以使用的 .lib 文件,它具有类似 Apache 的分发许可证。


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

这意味着您希望将 Python 嵌入到您的 C 应用程序中。如在另一个应用程序中嵌入 Python 中所述:

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.

我建议你先了解在另一个应用程序中嵌入 Python。然后参考以下示例

  • 在 C/C 中嵌入 Python:第一部分

  • 在 C/C 中嵌入 Python:第二部分

  • 在多线程 C/C 应用程序中嵌入 Python

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

  • 用 Boost.Python 嵌入 Python 第 1 部分

  • Boost 有一个 python 接口库可以帮助你。

    Boost.Python


    有趣的是,还没有人提到 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 函数(称为嵌入)就这么简单(取自文档):

    1
    2
    3
    4
    5
    6
    7
    #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
    }

    使用系统调用从 C 运行 python 脚本

    1
    2
    3
    4
    5
    6
    7
    8
    #includeiostream
    #include cstdlib
    using namespace std;
    int main ()
    {
    int result = system("/usr/bin/python3 testGen1.py 1");
    cout  result;
    }

    在您的 C 应用程序中嵌入 Python 解释器将使您能够使用您的应用程序运行 Python 脚本来运行 Python 程序。它还将使这些脚本更容易在您的应用程序中调用 C 函数。如果这是您想要的,那么前面提到的 Boost 库可能就是您想要更容易创建链接的东西。过去,我使用 SWIG 为 C 代码生成 Python 接口。从您的问题中不清楚您是希望 Python 脚本调用您的 C 程序还是只是希望 C 调用 Python。

    许多 Python 函数使用未内置在 Python 解释器中的模块。如果您的 Python 脚本调用这些函数,那么您将需要让您的用户安装 Python 或在您的应用程序中包含 Python 运行时文件。这将取决于您在 Python 脚本中导入的模块。


    Boost 可能是最好的选择,但是,如果您想要更独立的东西,并且如果这适用于 Windows(这似乎是可行的,因为他们是最不可能安装 Python 的人),那么您可以使用 py2exe 创建一个带有适合 COM 对象的入口点的 DLL。然后,您可以通过 COM 与库进行交互。 (显然,这作为跨平台解决方案一点用处都没有)。


    通过套接字使用进程间通信 (IPC) 可能是一种可能的解决方案。使用本地网络套接字在两者之间侦听/传输命令。


    展开全文阅读

    相关内容