如何导出std :: vector

Max*_*rai 9 c++ python string boost export

我正在使用boost.python库编写应用程序.我想将函数传递给返回的python std::vector.我有点麻烦:

inline std::vector<std::string> getConfigListValue(const std::string &key)
{
    return configManager().getListValue(key);
}

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue);
}
Run Code Online (Sandbox Code Playgroud)

当我从python调用该函数时,我得到:

TypeError: No to_python (by-value) converter found for C++ type: std::vector<std::string, std::allocator<std::string> >
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Fáb*_*niz 10

你应该写一个像这样的转换器:

template<class T>
struct VecToList
{
    static PyObject* convert(const std::vector<T>& vec)
    {
        boost::python::list* l = new boost::python::list();
        for(size_t i = 0; i < vec.size(); i++) {
            l->append(vec[i]);
        }

        return l->ptr();
    }
};
Run Code Online (Sandbox Code Playgroud)

然后在您的模块中注册:

BOOST_PYTHON_MODULE(MyModule)
{
    boost::python::to_python_converter<std::vector<std::string, std::allocator<std::string> >, VecToList<std::string> >();
    boost::python::def("getListValue", getListValue);
}
Run Code Online (Sandbox Code Playgroud)