2012-01-30 65 views
6

Tôi muốn sử dụng python nhúng trong C++ ứng dụng và chức năng gọi được xác định trong tập lệnh python. Tham số của hàm là đối tượng C++. Xem mã của tôi:chuyển đối tượng C++ vào hàm python bằng cách tăng :: python

class Test 
{ 
public: 
    void f() 
    { 
     std::cout<<"sss"<<std::endl; 
    } 
}; 

int main() 
{ 
    Py_Initialize(); 
    boost::python::object main = boost::python::import("__main__"); 
    boost::python::object global(main.attr("__dict__")); 
    boost::python::object result = boost::python::exec_file("E:\\python2.py", global, global); 
    boost::python::object foo = global["foo"]; 
    if(!foo.is_none()) 
    { 
     boost::python::object pyo(boost::shared_ptr<Test>(new Test())); // compile error 
     foo(pyo); 
    } 
    return 0; 
} 

python2.py:

def foo(o): 
    o.f() 

Làm thế nào để vượt qua C++ đối tượng để foo? Tôi biết swig có thể làm điều đó, nhưng tăng :: python?

+0

thể trùng lặp của [Tăng-python Làm thế nào để vượt qua một C++ lớp dụ về một lớp python] (http://stackoverflow.com/questions/5055443/boost-python-how-to -loại-ac-class-instance-to-a-python-class) –

Trả lời

2

Giải Quyết.

class Test 
{ 
public: 
    void f() 
    { 
     std::cout<<"sss"<<std::endl; 
    } 
}; 
//==========add this============ 
BOOST_PYTHON_MODULE(hello) 
{ 
    boost::python::class_<Test>("Test") 
     .def("f", &Test::f) 
    ; 
} 
//=============================== 
int main() 
{ 
    Py_Initialize(); 
//==========add this============ 
    inithello(); 
//=============================== 
    boost::python::object main = boost::python::import("__main__"); 
    boost::python::object global(main.attr("__dict__")); 
    boost::python::object result = boost::python::exec_file("E:\\python2.py", global, global); 
    boost::python::object foo = global["foo"]; 
    if(!foo.is_none()) 
    { 
     boost::shared_ptr<Test> o(new Test); 
     foo(boost::python::ptr(o.get())); 
    } 
    return 0; 
} 

another topic

Các vấn đề liên quan