pybind11和numpy进行交互的方法
Python  /  管理员 发布于 5年前   817
使用一个遵循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进行交互的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号