2012-01-30 95 views
6

我想在C++應用程序中使用嵌入python並調用python腳本中定義的函數。該函數的參數是一個C++對象。見我的代碼:將C++對象傳遞給python函數by boost :: 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() 

如何通過C++對象爲foo?我知道swig可以做到這一點,但boost :: python?

+0

[升壓-蟒如何C++類實例傳遞給一個python類(的可能重複http://stackoverflow.com/questions/5055443/boost-python-how-to -pass-AC-類實例到一個的Python類) – 2012-02-01 00:22:02

回答

2

解決。

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