4

How can I construct a boost::python::object from a std::function ?

1 Answer 1

6

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)'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.