假设我有一个像这样的
Python类:
class MyPythonClass:
def Func1(self, param):
return
def Func2(self, strParam):
return strParam
如果我想在我的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");
但是我尝试过的这段代码的许多变化并没有奏效.为了能够做到这一点,我需要为我的代码注入什么魔法酱?
最佳答案 这最终对我有用.
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");
如果有更好的方法,请随意评论.