英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论