Created
September 2, 2020 04:15
-
-
Save e2thenegpii/bcd119c37edfccdd8ff71b03d174a4a9 to your computer and use it in GitHub Desktop.
pybind11 getting arguments in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pybind11/pybind11.h> | |
namespace py = pybind11; | |
template<typename T> | |
T get_argument(const char* name, int& index, const py::args& args, const py::kwargs& kwargs) | |
{ | |
if(kwargs.contains(name)) | |
{ | |
return kwargs[name].cast<T>(); | |
} | |
else if(py::len(args) > index) | |
{ | |
return args[index++].cast<T>(); | |
} | |
throw std::invalid_argument(std::string(name) + " is a required parameter"); | |
} | |
PYBIND11_MODULE(example, m){ | |
m.doc() = "Pybind11 example plugin"; | |
m.def("add", [](int foo = 0, py::args args, py::kwargs kw){ | |
int args_idx = 0; | |
auto key = get_argument<py::buffer>("key", args_idx, args, kw); | |
auto iv = get_argument<py::buffer>("iv", args_idx, args, kw); | |
return foo; | |
}, py::arg("foo") = 0, "A function to add two numbers"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment