首页 > 解决方案 > 如何使用 Boost 从 numpy ndarray 中提取 Eigen MatrixXd

问题描述

在 Boost 的文档中,该extract函数用于将内置的 python 数据类型转换为 c++ 数据类型。我有一个返回 numpy ndarray 的 python 函数,在我的 c++ 代码中我想将它转换为 Eigen MatrixXd。所以,我想知道是否可以将非内置 python 类型提取为非内置 c++ 类型。

标签: pythonnumpyboost-python

解决方案


您需要编写 numpy ndarray 和 c++ Eigen:::MatrixXd 之间的转换并将其注册到 boost python 注册表中。

看起来像这样

namespace py = boost::python
template <typename MatrixType>
struct pyToEigen {
  pyToEigen() {
    py::converter::registry::push_back(&convertible, &construct, py::type_id<MatrixType>());
   }
  static void* convertible(PyObject* obj_ptr) {
    // check for if object is convetible here
  }
  static void construct(PyObject* obj_ptr, py::converter::rvalue_from_python_stage1_data* data) {
    // Construct here
  }
}:

我编写了一个仅包含标头的库来完成这项工作:https ://github.com/vsamy/pygen-converter 您只需要调用pygen::converter(Converters::All, true)即可带来几个不同的转换。

这种方法的主要缺点之一是它会复制所有内容。


推荐阅读