2017-02-10 22 views
2

假设我有一个Python类,像这样的应用实例:如何创建和使用升压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"); 

但这种代码,我已经试过没有工作的许多变化。为了能够做到这一点,我需要倾注我的代码的魔力酱是什么?

回答

0

这是最终为我工作的。

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"); 

如果有更好的方法,随意评论。