2017-02-10 47 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"); 

如果有更好的方法,隨意評論。