2011-03-30 133 views
1

通行證功能參考我在C++這樣的功能:與升壓蟒

typedef boost::function<boost::shared_ptr<Object> (CL_DomElement*, std::string& desc)> Parser; 
void registerParser(std::string type, Parser p); 

// Later: exporting into python-module: 
BOOST_PYTHON_MODULE(TypesManager) 
{ 
    bp::def("RegisterParser", registerParser); 
} 

# Python code: 
class TestObj(Object): 
    @staticmethod 
    def ParseTestObj(node, desc): 
     pass 

RegisterParser("test_obj", TestObj.ParseTestObj) 

對象在Python代碼導出其在使用的typedef類(從C++代碼)。

Boost.Python.ArgumentError: Python argument types in 
    RegisterParser(str, function) 
did not match C++ signature: 
    RegisterParser(TypesManager {lvalue}, std::string, boost::function<boost::shared_ptr<Object>()(CL_DomElement*, std::string&)>) 

我做錯了什麼?

回答

1

我不相信Boost Python理解如何將python函數轉換爲boost :: function對象。我會建議使用代理來獲取python可調用對象並模仿C++接口。快速示例模擬(當然未經測試):

typedef boost::function<boost::shared_ptr<Object> (CL_DomElement*, std::string& desc)> Parser; 
void registerParser(std::string type, Parser p); 

struct ParserProxy 
{ 
    bp::object callable; 

    ParserProxy(bp::object callable) 
    : callable(callable) 
    { } 

    boost::shared_ptr<Object> operator()(CL_DomElement* elem, std::string& desc) 
    { 
     bp::object obj = callable(elem, desc); 
     return bp::extract<boost::shared_ptr<Object> >(obj); 
    } 
}; 

void registerParserByProxy(std::string type, bp::object callable) 
{ 
    registerParser(type, ParserProxy(callable)); 
} 

// Later: exporting into python-module: 
BOOST_PYTHON_MODULE(TypesManager) 
{ 
     bp::def("RegisterParser", registerParserByProxy); 
}