Python embedded in CPP: how to get data back to CPP

前端 未结 4 2207
一向
一向 2020-12-05 20:01

While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what\'s need

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 20:19

    Based on ΤΖΩΤΖΙΟΥ, Josh and Nosklo's answers i finally got it work using boost.python:

    Python:

    import thirdparty
    
    def MyFunc(some_arg):
        result = thirdparty.go()
        return result
    

    C++:

    #include 
    #include 
    #include 
    
    using namespace boost::python;
    
    int main(int, char **) 
    {
        Py_Initialize();
    
        try 
        {
            object module = import("__main__");
            object name_space = module.attr("__dict__");
            exec_file("MyModule.py", name_space, name_space);
    
            object MyFunc = name_space["MyFunc"];
            object result = MyFunc("some_args");
    
            // result is a dictionary
            std::string val = extract(result["val"]);
        } 
        catch (error_already_set) 
        {
            PyErr_Print();
        }
    
        Py_Finalize();
        return 0;
    }
    

    Some important points:

    1. I changed 'exec' to 'exec_file' out of convenience, it also works with plain 'exec'.
    2. The main reason it failed is that i did not pass a "local" name_sapce to 'exec' or 'exec_file' - this is now fixed by passing name_space twice.
    3. If the python function returns unicode strings, they are not convertible to 'std::string', so i had to suffix all python strings with '.encode('ASCII', 'ignore')'.

提交回复
热议问题