如何使用boost :: python创建和使用Python对象的实例

cap*_*aps 6 c++ boost boost-python

假设我有一个像这样的Python类:

class MyPythonClass:
    def Func1(self, param):
        return
    def Func2(self, strParam):
        return strParam
Run Code Online (Sandbox Code Playgroud)

如果我想在我的C ++代码中嵌入包含该类的Python脚本,请通过我的C ++代码创建该对象的实例,然后在该python对象上调用成员,我该如何处理?

我认为应该是这样的:

namespace python = boost::python;
python::object main = python::import("main");
python::object mainNamespace = main.attr("__dict__");
python::object script = python::exec_file(path_to_my_script, mainNamespace);
python::object foo = mainNamespace.attr("MyPythonClass")();
python::str func2return = foo.attr("Func2")("hola");
assert(func2return == "hola");
Run Code Online (Sandbox Code Playgroud)

但是我尝试过的此代码的许多变体都没有用。为了做到这一点,我需要在代码中注入什么魔力?

cap*_*aps 5

这才是最终为我工作的东西。

namespace python = boost::python;
python::object main = python::import("main");
python::object mainNamespace = main.attr("__dict__");

//add the contents of the script to the global namespace
python::object script = python::exec_file(path_to_my_script, mainNamespace);

//add an instance of the object to the global namespace
python::exec("foo = MyPythonClass()", mainNamespace);
//create boost::python::object that refers to the created object
python::object foo = main.attr("foo");

//call Func2 on the python::object via attr
//then extract the result into a const char* and assign it to a std::string
//the last bit could be done on multiple lines with more intermediate variables if desired
const std::string func2return = python::extract<const char*>(foo.attr("Func2")("hola"));
assert(func2return == "hola");
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法,请随时发表评论。