How do I capture numpy and numpy-like buffer with template arguments using the same function? #5066
-
I am trying to write functions on C++ side that can accept a auto numpy_lambda = []<typename dfloat>(py::array_t<dfloat> &phi) {
py::buffer_info phi_info = phi.request();
dfloat *phi_ptr = reinterpret_cast<dfloat *>(phi_info.ptr);
my_func(phi_info.size, phi_ptr);
};
PYBIND11_MODULE(my_module, m) {
m.def("my_func", [](py::array_t<double> &phi) {
numpy_lambda.template operator()<double>(phi);
});
m.def("my_func", [](py::array_t<float> &phi) {
numpy_lambda.template operator()<float>(phi);
});
} This way I can use But now, I want to construct Another solution would be to write a different lambda function for So I want to understand, what is the appropriate solution in this case? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found the solution to my query. It was simple actually! The key is to simply change the prototype of the lambda function and rely on the overloading within python module. Finally it would look like this: auto lambda = []<typename dfloat>(py::buffer &phi) {
py::buffer_info phi_info = phi.request();
dfloat *phi_ptr = reinterpret_cast<dfloat *>(phi_info.ptr);
my_func(phi_info.size, phi_ptr);
};
PYBIND11_MODULE(my_module, m) {
m.def("my_func", [](py::array_t<double> &phi) {
lambda.template operator()<double>(phi);
});
m.def("my_func", [](py::array_t<float> &phi) {
lambda.template operator()<float>(phi);
});
m.def("my_func", [](foo::array_t<double> &phi) {
lambda.template operator()<double>(phi);
});
m.def("my_func", [](foo::array_t<double> &phi) {
lambda.template operator()<double>(phi);
});
} |
Beta Was this translation helpful? Give feedback.
I found the solution to my query. It was simple actually! The key is to simply change the prototype of the lambda function and rely on the overloading within python module. Finally it would look like this: