pybind11和numpy进行交互的方法

yipeiwu_com5年前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设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Flask之pipenv虚拟环境的实现

在 python 开发过程中,导入第三方库是最常见的操作,但是如果咋在本机自带 python 环境下安装第三方包。 就会造成库的冗余,比如某个项目只需要部分第三方库,但是其他项目又需要其...

python处理Excel xlrd的简单使用

xlrd主要用于读取Excel文件,本文为大家分享了python处理Excel的具体代码,供大家参考,具体内容如下 安装 pip install xlrd api使用 im...

python中(str,list,tuple)基础知识汇总

python是一门动态解释型的强类型定义语言(先编译后解释) 动态类型语言 动态类型的语言编程时,永远也不用给任何变量指定数据类型,该语言会在你第一次赋值给变量时,在内部将数据类型记录下...

python程序 线程队列queue使用方法解析

一、线程队列 queue队列:使用方法同进程的Queue一样 如果必须在多个线程之间安全地交换信息时,队列在线程编程中尤其有用。 重要: q.put() :往队列里面放值,当参数blo...

python入门教程之识别验证码

python入门教程之识别验证码

前言 验证码?我也能破解? 关于验证码的介绍就不多说了,各种各样的验证码在人们生活中时不时就会冒出来,身为学生日常接触最多的就是教务处系统的验证码了,比如如下的验证码: 识别办法...