溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

pybind11和numpy如何進行交互

發(fā)布時間:2021-08-18 10:10:52 來源:億速云 閱讀:262 作者:小新 欄目:開發(fā)技術

小編給大家分享一下pybind11和numpy如何進行交互,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

使用一個遵循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;
};

其實就是一個指向數(shù)組的指針+各個維度的信息就可以了. 然后我們就可以用指針+偏移來訪問數(shù)字中的任意位置上的數(shù)字了.

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

#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中可以得到指針和對應數(shù)字的維度信息.

為了方便我們甚至可以使用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);
 }

以上是“pybind11和numpy如何進行交互”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI