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

发布于 2024-12-09 14:20:57 字数 51 浏览 2 评论 0原文

如何从 std::function 构造 boost::python::object ?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够 2024-12-16 14:20:57

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

我们可以定义一个包装器并使用它的 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);
}

Python 端现在可以按照我们想要的方式使用结果:

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

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)'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文