【问题标题】:Creating python collections.namedtuple from C++ using boost::python使用 boost::python 从 C++ 创建 python collections.namedtuple
【发布时间】:2012-12-03 00:02:37
【问题描述】:

我想从 boost::python 包装函数返回collections.namedtuple 的列表,但我不确定如何从 C++ 代码创建这些对象。对于其他一些类型,有一个方便的包装器(例如 dict),这使得这很容易,但对于 namedtuple 却没有这样的东西。最好的方法是什么?

dict列表的现有代码:

namespace py = boost::python;

struct cacheWrap {
   ...
   py::list getSources() {
      py::list result;
      for (auto& src : srcCache) {  // srcCache is a C++ vector
         // {{{ --> Want to use a namedtuple here instead of dict
         py::dict pysrc;
         pysrc["url"] = src.url;
         pysrc["label"] = src.label;
         result.append(pysrc);
         // }}}
      }
      return result;
   }
   ...
};


BOOST_PYTHON_MODULE(sole) {
   py::class_<cacheWrap,boost::noncopyable>("doc", py::init<std::string>())
      .def("getSources", &cacheWrap::getSources)
   ;
}

【问题讨论】:

  • A namedtupletuple 的子类,所以也许你可以从处理前者的代码开始并相应地修改它。

标签: c++ python python-3.x boost-python


【解决方案1】:

下面的代码完成了这项工作。更好的解决方案会得到检验。

在 ctor 中执行此操作以设置字段 sourceInfo:

auto collections = py::import("collections");
auto namedtuple = collections.attr("namedtuple");
py::list fields;
fields.append("url"); 
fields.append("label");
sourceInfo = namedtuple("Source", fields);

新方法:

py::list getSources() {
   py::list result;
   for (auto& src : srcCache)
      result.append(sourceInfo(src.url, src.label));
   return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多