PyBind很棒,向作者/维护者致敬!你可以在这里找到一个几乎可用的示例。
根据你的问题进行调整后,它可能会给出类似以下的答案(在El Dude的评论后进行了编辑):
#include <iostream>
#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();
py::buffer_info buf2 = input2.request();
if (buf1.size != buf2.size) {
throw std::runtime_error("Input shapes must match");
}
py::array_t<double> 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;
int X = buf1.shape[0];
int Y = buf1.shape[1];
for (size_t idx = 0; idx < X; idx++) {
for (size_t idy = 0; idy < Y; idy++) {
ptr3[idx*Y + idy] = ptr1[idx*Y+ idy] + ptr2[idx*Y+ idy];
}
}
result.resize({X,Y});
return result;
}
PYBIND11_MODULE(example, m) {
m.doc() = "Add two vectors using pybind11";
m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
}
我在Linux上使用Python2.7和GCC v5.4构建(由于没有找到Python.h,因此我必须使用略有不同的命令,因此我添加了指向Python 2.7的链接)
c++ -O3 -Wall -shared -std=c++11 -fPIC -I/usr/include/python2.7 -lpython2.7 `python -m pybind11 --includes` example.cpp -o example`python-config --extension-suffix
你可以通过Python调用它:
import numpy as np
import example # [bad] name I chose for my compiled module
a = np.zeros((10,3))
b = np.ones((10,3)) * 3
c = example.add_arrays(a, b)
print c
希望能对您有帮助。
编辑 - 我创建了一个GitHub存储库,其中包含一些基于PyBind11的完整示例,可在所有平台上编译。