2011-03-30 109 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); 
}