用元组参数调用 pybind11 的函数?

huangapple go评论86阅读模式
英文:

Call pybind11:function with tupled arguments?

问题

在C++中,我需要调用Python函数,这些函数可以具有任意数量的参数。

是否可以使用元组参数来调用pybind函数对象,类似于PyObject_CallObject(https://docs.python.org/3/c-api/call.html#object-calling-api)?

我尝试使用()操作符和.call()方法传递元组参数,但它似乎期望精确的参数而不是元组参数(报错:缺少1个必需的位置参数)。

英文:

In C++, I need to invoke Python functions that can have any number of arguments.

Is it possible to invoke a pybind function object with tupled arguments, similar to PyObject_CallObject (https://docs.python.org/3/c-api/call.html#object-calling-api)?

I tried passing tupled arguments with () operator and the .call() method, but it seems to be expecting the exact arguments instead of tupled argument (missing 1 required positional argument).

答案1

得分: 1

你可以直接使用 pybind11 解包 Python 的元组

py::function callable = ...;
py::tuple args = ...;
callable(*args);

详见 unpacking arguments 在 pybind11 文档中的说明。


值得注意的是,如果你有一个 C++ 元组,你可以使用 std::apply

py::function callable = ...;
std::tuple<int, int> args = ...;
std::apply(callable, args);
英文:

You can directly unpack Python tuples with pybind11

py::function callable = ...;
py::tuple args = ...;
callable(*args);

See unpacking arguments in pybind11 documentation.


Worth noting that if you have a C++ tuple, you can use std::apply

py::function callable = ...;
std::tuple<int, int> args = ...;
std::apply(callable, args);

huangapple
  • 本文由 发表于 2023年3月9日 22:52:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定