Search code examples
pythonc++pybind11

Using pybind11 to expose C++ functionality with preexisting embedded python interpreter


I am trying this type of coding for the first time and hence please pardon my lack of knowledge.

Requirement: I have a C++ code in which I have embedded python interpreter so that i can import/use python libraries with C++ using pybind11. Further, I want to make a wrapper of this complete C++ code (along with python interpreter part) and expose it to python as a module. Consider the below example for clarity:

**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;
    }

I want to expose this code to python (say as a module named Cpp_func) and import in py script using "import Cpp_func"

What I have tried till now: Using pybind11, I could manage to extend a sample cpp code without python interpreter embedded to python. Example was taken from the pybind11 docs https://pybind11.readthedocs.io/en/latest/basics.html 'Creating bindings for a simple function' section. But I am unable to figure out how to do the same when a python interpreter is already embedded into C++ code.

Hope my requirement is clear. Any comments on this would be really helpful!

Thanks in advance!


Solution

  • scoped_interpreter_guard is just a RAII wrapper around initialize_interpreter and finalize_interpreter. You can just call finalize_interpreter yourself instead of Py_Finalize.