简体   繁体   中英

Pybind11 - Function with unknown number of arguments

I want to get a list of arguments

my current c++ code:

m.def("test", [](std::vector<pybind11::object> args){
    return ExecuteFunction("test", args);
});

my current python code:

module.test(["-2382.430176", "-610.183594", "12.673874"])
module.test([])

I want my python code to look like this:

module.test("-2382.430176", "-610.183594", "12.673874")
module.test()

How can I get all arguments passed through Python?

Such generic functions module.test(*args) can be created using pybind11:

void test(py::args args) {
    // do something with arg
}

// Binding code
m.def("test", &test);

Or

m.def("test", [](py::args args){
    // do something with arg
});

See Accepting *args and **kwargs and the example for more details.

m.def("test", [](const pybind11::args& args){ std::vector<pybind11::object> pyArgs; for (const auto &arg : args) { pyArgs.push_back(arg.cast<pybind11::object>()); } return ExecuteFunction("test", pyArgs); });

I have to admit I'm not entirely sure what you're trying to do, but here is one idea:

def wrapper(args*)
    return module.test(args)

There are other ways of making such a wrapper but this should work if I understand your question correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM