您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Boost :: Python-可以自动从dict-> std :: map转换吗?

Boost :: Python-可以自动从dict-> std :: map转换吗?

我认为,有两种方法比编写自己的转换器更容易实现。您可以使用boost :: python的map_indexing_suite为您进行转换,也可以在python中使用关键字参数。我个人更喜欢关键字参数,因为这是更“ Pythonic”的方式。

这是您的课程(我为地图添加了typedef):

typedef std::map<std::string, double> MyMap;

class myClass {
public:
    // Constructors - set a-f to default values.

    void SetParameters(MyMap &);
private:
    double a, b, c, d, e, f;
};

使用map_indexing_suite的示例:

#include <boost/python/suite/indexing/map_indexing_suite.hpp>

using boost::python;

BOOST_PYTHON_MODULE(mymodule)
{
    class_<std::map<std::string, double> >("MyMap")
        .def(map_indexing_suite<std::map<std::wstring, double> >() );

    class_<myClass>("myClass")
        .def("SetParameters", &myClass::SetParameters);
}

使用关键字参数的示例。这需要使用raw_function包装器:

using namespace boost::python;

object SetParameters(tuple args, dict kwargs)
{
    myClass& self = extract<myClass&>(args[0]);

    list keys = kwargs.keys();

    MyMap outMap;
    for(int i = 0; i < len(keys); ++i) {
        object curArg = kwargs[keys[i]];
        if(curArg) {
            outMap[extract<std::string>(keys[i])] = extract<double>(kwargs[keys[i]]);
        }               
    }
    self.SetParameters(outMap);

    return object();
}

BOOST_PYTHON_MODULE(mymodule)
{
    class_<myClass>("myClass")
        .def("SetParameters", raw_function(&SetParameters, 1));
}

这使您可以在Python中编写如下内容

A.SetParameters(a = 2.2, d = 4.3, b = 9.3)
python 2022/1/1 18:42:16 有357人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶