4

我想collections.namedtuple从 boost::python 包装函数返回一个列表,但我不确定如何从 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)
   ;
}
4

1 回答 1

8

The following code does the job. Better solutions will get the check.

Do this in ctor to set field sourceInfo:

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

New method:

py::list getSources() {
   py::list result;
   for (auto& src : srcCache)
      result.append(sourceInfo(src.url, src.label));
   return result;
}
于 2012-12-03T21:02:53.770 回答