【问题标题】:boost::python convert std::arrayboost::python 转换 std::array
【发布时间】:2013-08-23 14:34:21
【问题描述】:

我正在使用 std::array 为最短路径函数定义 2D 点。

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

目前,我最好的解决方案是将点 (std::array) 转换为 std::vector,并使用 boost::python::vector_indexing_suite 作为:

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

是否可以直接从/到 std::array 到/从 python 索引或转换?

【问题讨论】:

  • This 回答可能会有所帮助。它展示了如何为集合注册自定义转换器,包括多个维度。

标签: c++ boost-python stdarray


【解决方案1】:

为了让它看起来像pythonic,我会使用boost::python::extract、tuple和list的组合。这是一个草图:

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

那么绑定将如下所示:

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

【讨论】:

  • 很好的答案!我整天都在寻找这样的解决方案,非常有帮助!
猜你喜欢
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2012-05-23
  • 2018-05-25
  • 2015-01-24
相关资源
最近更新 更多