Skip to content

Instantly share code, notes, and snippets.

@e2thenegpii
Created September 2, 2020 04:15
Show Gist options
  • Save e2thenegpii/bcd119c37edfccdd8ff71b03d174a4a9 to your computer and use it in GitHub Desktop.
Save e2thenegpii/bcd119c37edfccdd8ff71b03d174a4a9 to your computer and use it in GitHub Desktop.
pybind11 getting arguments in c++
#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