pybind11和numpy进行交互的方法

yipeiwu_com6年前Python基础

使用一个遵循buffer protocol的对象就可以和numpy交互了.

这个buffer_protocol要有哪些东西呢? 要有如下接口:

struct buffer_info {
  void *ptr;
  ssize_t itemsize;
  std::string format;
  ssize_t ndim;
  std::vector<ssize_t> shape;
  std::vector<ssize_t> strides;
};

其实就是一个指向数组的指针+各个维度的信息就可以了. 然后我们就可以用指针+偏移来访问数字中的任意位置上的数字了.

下面是一个可以跑的例子:

#include <pybind11/pybind11.h>
 #include <pybind11/numpy.h>
 namespace py = pybind11;
 py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
   py::buffer_info buf1 = input1.request(), buf2 = input2.request();
   if (buf1.ndim != 1 || buf2.ndim != 1)
     throw std::runtime_error("Number of dimensions must be one");
   if (buf1.size != buf2.size)
     throw std::runtime_error("Input shapes must match");
   /* No pointer is passed, so NumPy will allocate the buffer */
   auto result = py::array_t<double>(buf1.size);
   py::buffer_info buf3 = result.request();
   double *ptr1 = (double *) buf1.ptr,
      *ptr2 = (double *) buf2.ptr,
      *ptr3 = (double *) buf3.ptr;
   for (size_t idx = 0; idx < buf1.shape[0]; idx++)
     ptr3[idx] = ptr1[idx] + ptr2[idx];
   return result;
 }
 
 PYBIND11_MODULE(test, m) {
   m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
 }

array_t里的buf就是一个兼容的接口.

buf中可以得到指针和对应数字的维度信息.

为了方便我们甚至可以使用Eigen当作我们兼容numpy的接口:

#include <pybind11/pybind11.h>
 #include <pybind11/eigen.h> 
 #include <Eigen/LU> 
 // N.B. this would equally work with Eigen-types that are not predefined. For example replacing
 // all occurrences of "Eigen::MatrixXd" with "MatD", with the following definition:
 //
 // typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatD;
 
 Eigen::MatrixXd inv(const Eigen::MatrixXd &xs)
 {
  return xs.inverse();
 }
 
 double det(const Eigen::MatrixXd &xs)
 {
  return xs.determinant();
 }
 
 namespace py = pybind11;
 
 PYBIND11_MODULE(example,m)
 {
  m.doc() = "pybind11 example plugin";
 
  m.def("inv", &inv);
 
  m.def("det", &det);
 }

更多参考:

https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html

https://github.com/tdegeus/pybind11_examples

总结

以上所述是小编给大家介绍的pybind11和numpy进行交互的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

使用Python轻松完成垃圾分类(基于图像识别)

使用Python轻松完成垃圾分类(基于图像识别)

0 环境 Python版本:3.6.8 系统版本:macOS Mojave Python Jupyter Notebook 1 引言 七月了,大家最近一定被一项新的政策给折磨的焦头烂...

python自动化工具日志查询分析脚本代码实现

受控节点slave.py 复制代码 代码如下:import socketimport reclass Log(object):    file_list=[...

Python list操作用法总结

Python list操作用法总结

本文实例讲述了Python list操作用法。分享给大家供大家参考,具体如下: List是python中的基本数据结构之一,和Java中的ArrayList有些类似,支持动态的元素的增加...

使用python3实现操作串口详解

通过引用serial模块包,来操作串口。 1、查看串口名称 在Linux和Windows中,串口的名字规则不太一样。 需要事先查看。 Linux下的查看串口命令 root@D2:...

让你的Python代码实现类型提示功能

Python是一种动态类型语言,这意味着我们在编写代码的时候更为自由,但是与此同时IDE无法向静态类型语言那样分析代码,及时给我们相应的提示。为了解决这个问题,Python 3.6 新增...