使用boost :: python从C创建python collections.namedtuple

我想从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)
   ;
}

最佳答案 以下代码完成了这项工作.更好的解决方案将得到检查.

在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;
}
点赞