开发者

Creating a boost::python::object from a std::function

How can I construct a boost::python::object from a std::func开发者_如何学编程tion ?


Use boost::python::make_function, and provide a signature because the default one doesn't handle std::function.

For example, we want to wrap the return type of:

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) + ")";
    };
}

We could define a wrapper and def using it:

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);
}

The Python side can now use the result as we want:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜