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数据可视化:箱线图多种库画法

概念 箱线图通过数据的四分位数来展示数据的分布情况。例如:数据的中心位置,数据间的离散程度,是否有异常值等。 把数据从小到大进行排列并等分成四份,第一分位数(Q1),第二分位数(Q2)和...

python 判断linux进程,并杀死进程的实现方法

如下所示: ''' @author: Jacobpc ''' import os import sys import subprocess def get_process_id(...

python 实现dict转json并保存文件

如下所示: import json f = open("index.html", "wb") json.dump(response.data, f) f.close() dum...

用python打印菱形的实操方法和代码

python怎么打印菱形?下面给大家带来三种方法: 第一种 rows = int(input('请输入菱形边长:\n')) row = 1 while row <= row...

python实现微信发送邮件关闭电脑功能

Python 通过微信邮件实现电脑关机,供大家参考,具体内容如下 通过手机微信发送QQ邮件给sina邮箱,然后利用python的pop3定时检查sina邮箱的邮件主题以及邮件来源,并在电...