我在 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&)>)
我做错了什么?
最佳答案
我不相信 Boost Python 理解如何将 python 函数转换为 boost::function 对象。我的建议是使用代理获取 python 可调用对象并模仿 C++ 接口(interface)。快速示例模型(当然未经测试):
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);
}
关于c++ - 使用 boost python 传递函数引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490962/