使用pybind11通过预先存在的嵌入式python解释器公开C ++功能

问题描述

我第一次尝试这种类型的编码,因此请原谅我缺乏的知识。

要求:我有一个C ++代码,其中嵌入了python解释器,以便可以使用pybind11在C ++中导入/使用python库。此外,我想包装这个完整的C ++代码(以及python解释器部分),并将其作为模块公开给python。为了清楚起见,请考虑以下示例:

**Main_code.cpp:**

    #include <iostream>
    #include <pybind11/embed.h> // everything needed for embedding
    
    int main() {
        pybind11::scoped_interpreter guard{}; // start the interpreter and keep it alive
        pybind11::module sys = pybind11::module::import("sys");
        pybind11::print(sys.attr("path"));
        return 0;
    }

我想将此代码公开给python(例如,名为Cpp_func的模块),然后使用“ import Cpp_func”导入py脚本

到目前为止我一直在尝试: 使用pybind11,我可以设法扩展示例cpp代码,而无需将python解释器嵌入到python中。示例取自pybind11 docs https://pybind11.readthedocs.io/en/latest/basics.html“为简单函数创建绑定”部分。但是当Python解释器已经嵌入到C ++代码中时,我无法弄清楚该怎么做。

希望我的要求很明确。任何对此的评论将非常有帮助!

谢谢!

解决方法

scoped_interpreter_guard只是initialize_interpreterfinalize_interpreter周围的RAII wrapper。您可以自己拨打finalize_interpreter而不是Py_Finalize