从std :: function创建boost :: python :: object

And*_*uel 4 c++ python boost boost-python c++11

如何从std :: function构造boost :: python ::对象?

ken*_*ytm 5

使用boost::python::make_function,并提供签名,因为默认值不会处理std::function.

例如,我们想要包装返回类型:

std::function<std::string(int, int)> get_string_function(const std::string& name)
{
    return [=](int x, int y)
    {
        return name + "(x=" + std::to_string(x) + ", y=" + std::to_string(y) + ")";
    };
}
Run Code Online (Sandbox Code Playgroud)

我们可以定义一个包装器并def使用它:

boost::python::object get_string_function_pywrapper(const std::string& name)
{
    auto func = get_string_function(name);
    auto call_policies = boost::python::default_call_policies();
    typedef boost::mpl::vector<std::string, int, int> func_sig;
    return boost::python::make_function(func, call_policies, func_sig());
}

BOOST_PYTHON_MODULE(s)
{
    boost::python::def("get_string_function", get_string_function_pywrapper);
}
Run Code Online (Sandbox Code Playgroud)

Python方面现在可以根据需要使用结果:

>>> import s
>>> s.get_string_function("Coord")
<Boost.Python.function object at 0x1cca450>
>>> _(1, 4)
'Coord(x=1, y=4)'
Run Code Online (Sandbox Code Playgroud)