开发者

How to export std::vector

I'm writing application wiht boost.python library. I want to pass function into python which returnes std::vector. I have a little troubles:

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

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue);
}

When I call that function from python I get:

TypeError: No to_python (by-value) converter found for C++ type: std::vector<std::string, std::allocator<std::string>开发者_开发问答 >

What have I missed?


You should write a converter like this:

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();
    }
};

And then register it in your module:

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


It is a bit old question, but I've found that if you explicitly require to return by value, like so:

namespace bp = boost::python

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue,
            bp::return_value_policy<bp::return_by_value>());
}      

rather than

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue);
}

Python does the conversion for you (I am using Python 2.7 at the time of writing this answer) and there is no need to declare/define the converter.

@Tryskele


I use following utility functions to convert from/to stl containers. The trivial sum function illustrates how they are used. I hope you can use it.

#include <vector>
#include <boost/python.hpp>
#include <boost/python/object.hpp>
#include <boost/python/stl_iterator.hpp>

namespace bpy = boost::python;

namespace fm {

template <typename Container>
bpy::list stl2py(const Container& vec) {
  typedef typename Container::value_type T;
  bpy::list lst;
  std::for_each(vec.begin(), vec.end(), [&](const T& t) { lst.append(t); });
  return lst;
}

template <typename Container>
void py2stl(const bpy::list& lst, Container& vec) {
  typedef typename Container::value_type T;
  bpy::stl_input_iterator<T> beg(lst), end;
  std::for_each(beg, end, [&](const T& t) { vec.push_back(t); });
}

bpy::list sum(const bpy::list& lhs, const bpy::list& rhs) {
  std::vector<double> lhsv;
  py2stl(lhs, lhsv);

  std::vector<double> rhsv;
  py2stl(rhs, rhsv);

  std::vector<double> result(lhsv.size(), 0.0);
  for (int i = 0; i < lhsv.size(); ++i) {
    result[i] = lhsv[i] + rhsv[i];
  }
  return stl2py(result);
}

} // namespace fm

BOOST_PYTHON_MODULE(entry)
{
  // intended to be fast math's fast sum :)
  bpy::def("sum", &fm::sum);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜