【问题标题】:Creating a boost::python::object from a std::function从 std::function 创建 boost::python::object
【发布时间】:2011-12-06 04:30:28
【问题描述】:

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

【问题讨论】:

    标签: c++ python boost c++11 boost-python


    【解决方案1】:

    Use 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)'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      相关资源
      最近更新 更多