You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

svl_wrapper.cpp 2.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include<iostream>
  2. #include<pybind11/pybind11.h>
  3. #include<pybind11/numpy.h>
  4. namespace py = pybind11;
  5. /* 1d Array + 1d Array */
  6. py::array_t<double> add_arrays_1d(py::array_t<double>& input1, py::array_t<double>& input2)
  7. {
  8. // Get info from input1, input2
  9. py::buffer_info buf1 = input1.request();
  10. py::buffer_info buf2 = input2.request();
  11. if (buf1.ndim !=1 || buf2.ndim !=1)
  12. {
  13. throw std::runtime_error("Number of dimensions must be one");
  14. }
  15. if (buf1.size !=buf2.size)
  16. {
  17. throw std::runtime_error("Input shape must match");
  18. }
  19. //Apply resources
  20. auto result = py::array_t<double>(buf1.size);
  21. py::buffer_info buf3 = result.request();
  22. //Obtain numpy.ndarray data pointer
  23. double* ptr1 = (double*)buf1.ptr;
  24. double* ptr2 = (double*)buf2.ptr;
  25. double* ptr3 = (double*)buf3.ptr;
  26. //Pointer visits numpy.ndarray
  27. for (int i = 0; i < buf1.shape[0]; i++)
  28. {
  29. ptr3[i] = ptr1[i] + ptr2[i];
  30. }
  31. return result;
  32. }
  33. /* 2d Matrix Add */
  34. py::array_t<double> add_arrays_2d(py::array_t<double>& input1, py::array_t<double>& input2)
  35. {
  36. py::buffer_info buf1 = input1.request();
  37. py::buffer_info buf2 = input2.request();
  38. if (buf1.ndim != 2 || buf2.ndim != 2)
  39. {
  40. throw std::runtime_error("numpy.ndarray dims must be 2!");
  41. }
  42. if ((buf1.shape[0] != buf2.shape[0])|| (buf1.shape[1] != buf2.shape[1]))
  43. {
  44. throw std::runtime_error("two array shape must be match!");
  45. }
  46. //Apply resources
  47. auto result = py::array_t<double>(buf1.size);
  48. //Resize to 2d array
  49. result.resize({buf1.shape[0],buf1.shape[1]});
  50. py::buffer_info buf_result = result.request();
  51. //Pointer reads and writes numpy.ndarray
  52. double* ptr1 = (double*)buf1.ptr;
  53. double* ptr2 = (double*)buf2.ptr;
  54. double* ptr_result = (double*)buf_result.ptr;
  55. for (int i = 0; i < buf1.shape[0]; i++)
  56. {
  57. for (int j = 0; j < buf1.shape[1]; j++)
  58. {
  59. auto value1 = ptr1[i*buf1.shape[1] + j];
  60. auto value2 = ptr2[i*buf2.shape[1] + j];
  61. ptr_result[i*buf_result.shape[1] + j] = value1 + value2;
  62. }
  63. }
  64. return result;
  65. }
  66. PYBIND11_MODULE(numpy_demo2, m) {
  67. m.doc() = "Simple demo using numpy!";
  68. m.def("add_arrays_1d", &add_arrays_1d);
  69. }