2017-02-10 1 views
2

내가 파이썬 클래스과 같이 있다고 가정의 : 내 C에서 그 클래스를 포함하는 파이썬 스크립트를 포함 할 경우를 만드는 방법 및 사용 인스턴스 부스트 파이썬 개체 :: 파이썬

class MyPythonClass: 
    def Func1(self, param): 
     return 
    def Func2(self, strParam): 
     return strParam 

++ 코드 내 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"); 

더 좋은 방법이 있으면 언제든지 댓글을 남길 수 있습니다.