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中可以得到指針和對應(yīng)數(shù)字的維度信息.
為了方便我們甚至可以使用Eigen當(dāng)作我們兼容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
總結(jié)
以上所述是小編給大家介紹的pybind11和numpy進行交互的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
python編程學(xué)習(xí)np.float 被刪除的問題解析
這篇文章主要為大家介紹了python編程學(xué)習(xí)np.float 被刪除的問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
淺談tensorflow與pytorch的相互轉(zhuǎn)換
本文主要介紹了簡單介紹一下tensorflow與pytorch的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

