Exposing a C++ class instance to a python embedded interpreter

后端 未结 3 493
醉梦人生
醉梦人生 2020-12-25 15:01

I am looking for a simple way to expose a C++ class instance to a python embedded interpreter.

  • I have a C++ library. This library is wrapped (using swig for th
3条回答
  •  不知归路
    2020-12-25 15:22

    For reference, here is how you can achieve this using pybind11:

    #include 
    #include 
    namespace py = pybind11;
    
    // Define C++ class "Foo"
    class Foo {
        std::string s_;
    public:
        Foo(const std::string &s) : s_(s) {}
        void doSomething() { std::cout << s_ << std::endl; }
    };
    typedef std::shared_ptr FooPtr;
    
    // Define Python module "bar" and Python class "bar.Foo" wrapping the C++ class
    PYBIND11_MODULE(bar, m) {
        py::class_(m, "Foo")
            .def("doSomething", &Foo::doSomething);
    }
    
    int main(int argc, char **argv)
    {
        // Create a C++ instance of Foo
        FooPtr foo = std::make_shared("Hello, World!");
    
        // Initialize Python interpreter and import bar module
        PyImport_AppendInittab("bar", PyInit_bar);
        Py_Initialize();
        PyRun_SimpleString("import bar");
    
        // Make C++ instance accessible in Python as a variable named "foo"
        py::module main = py::module::import("__main__");
        main.attr("foo") = foo;
    
        // Run some Python code using foo
        PyRun_SimpleString("foo.doSomething()");
    
        // Finalize the Python interpreter
        Py_Finalize();
        return 0;
    }
    

提交回复
热议问题