传递python中的List
pybind11 很贴心地帮你把 vector 跟 python 的 list 做好了转换,你只需要 #include 即可 [1]
C++端代码
#include
#include
#include
using std::vector;
namespace py = pybind11;
vector ListMul(vector& in_list, float coef) {
vector ret_vec;
ret_vec.clear();
ret_vec.reserve(in_list.size()); // Requests that the vector capacity be at least enough to contain n elements.
for (size_t i = 0; i < in_list.size(); ++i) {
int v = in_list[i];
ret_vec.push_back(coef * v);
}
return ret_vec;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pass and return a list";
m.def("ListMul", &ListMul, "example function");
}
python端调用
import example
print(example.ListMul([1.0, 2, 3, 4, 5, 6], 5))
类似地还有map在 python 里对应的就是 Dict[Tk, Tv] [1]。
传递Numpy 数组
两个数组相加的案例 [2]
C++端代码
#include
#include
namespace py = pybind11;
py::array_t add_arrays(py::array_t input1, py::array_t input2) {
// read input arrays buffer_info
py::buffer_info buf1 = input1.request(), buf2 = input2.request();
if (buf1.size != buf2.size)
throw std::runtime_error("Input shapes must match");
// allocate the output buffer
py::array_t result = py::array_t(buf1.size);
py::buffer_info buf3 = result.request(); // acquire buffer info
double *ptr1 = (double *)buf1.ptr, *ptr2 = (double *)buf2.ptr, *ptr3 = (double *)buf3.ptr;
size_t high = buf1.shape[0];
size_t width = buf1.shape[1];
// Add both arrays
for (size_t idy = 0; idy < high; idy++)
{
for (size_t idx = 0; idx < width; idx++)
{
int curIdx = idy*width + idx;
ptr3[curIdx] = ptr1[curIdx] + ptr2[curIdx];
}
}
/* Reshape result to have same shape as input */
result.resize({ high, width });
return result;
}
PYBIND11_MODULE(example, m) {
m.doc() = "Add two vectors using pybind11"; // optional module docstring
m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
}
python端调用
import numpy as np
import example
a = np.ones((10,3))
b = np.ones((10,3)) * 3
c = example.add_arrays(a, b)
print(c)
These numpy array arguments can either be generic py:array or typed py:array_t. The properties of the numpy array can be obtained by calling its request method. This returns a struct of the following form [3]:
struct buffer_info {
void *ptr;
size_t itemsize;
std::string format;
int ndim;
std::vector shape;
std::vector strides;
};
参考
这里面提供了很多丰富的案例