2012-12-03 89 views
3

我想从boost :: python包函数返回collections.namedtuple的列表,但我不确定如何从C++代码创建这些对象。对于其他一些类型,有一个方便的包装器(例如字典),这使得这很容易,但没有像namedtuple那样存在。做这个的最好方式是什么?对字典的名单使用boost :: python创建python collections.namedtple使用boost :: python

现有代码:

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) 
    ; 
} 
+0

一个'namedtuple'是tuple'的'一个子类,所以也许你可以开始用处理前者的代码并相应地修改它。 – martineau

回答

7

下面的代码做这项工作。更好的解决方案将得到检查。

为此在构造函数来设置现场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; 
}