Search code examples
c++boost-pythonstdarray

boost::python convert std::array


I'm using std::array to define 2D points for a shortest path function.

typedef std::array<double, 2> point_xy_t;
typedef std::vector<point_xy_t> path_t;
path_t search(const point_xy_t& start, const point_xy_t& goal);

For now, my best solution is to convert points ( std::array ) to std::vector, and use boost::python::vector_indexing_suite as:

bpy::class_<std::vector<double> >("Point")
    .def(bpy::vector_indexing_suite<std::vector<double> >())
;
bpy::class_<std::vector<std::vector<double>> >("Path")
    .def(bpy::vector_indexing_suite<std::vector<std::vector<double>> >())
;

Would it be possible to index or convert directly from/to std::array to/from python ?


Solution

  • To give it that pythonic look, I'd use a combination of boost::python::extract, tuple's and list's. Here is a sketch:

    static bpy::list py_search(bpy::tuple start, bpy::tuple goal) {
      // optionally check that start and goal have the required
      // size of 2 using bpy::len()
    
      // convert arguments and call the C++ search method
      std::array<double,2> _start = {bpy::extract<double>(start[0]), bpy::extract<double>(start[1])};
      std::array<double,2> _goal  = {bpy::extract<double>(goal[0]), bpy::extract<double>(goal[1])};
      std::vector<std::array<double,2>> cxx_retval = search(_start, _goal);
    
      // converts the returned value into a list of 2-tuples
      bpy::list retval;
      for (auto &i : cxx_retval) retval.append(bpy::make_tuple(i[0], i[1]));
      return retval;
    }
    

    Then the bindings would look like this:

    bpy::def("search", &py_search);