c++ - 使用 boost python 传递函数引用

标签 c++ python function boost export

我在 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/

相关文章:

c++ - QObject::connect: 无法对类型为 'QVector<int>' 的参数进行排队

c++ - 获取第三方Click-Once应用的config文件夹

javascript - 从 flask /python调用Javascript函数

python - Virtualenv 包含全局包/如何清除我的 PYTHONPATH?

c - 此示例导致c4028警告,为什么?

c++ - 为什么非递归方法比递归方法花费更多时间?

python - 在从 Python 调用的 C 函数中使用 PyFloat_FromDouble 时获得错误结果

javascript - 正则表达式来匹配 javascript 函数的定义并确保它返回一些东西?

python - 如何在Python中获取数学函数作为用户的输入并在循环中使用它

c++ - 将一个 slice_array 分配给另一个 slice_array 是否正确?