首页 > 解决方案 > pybind11:从 c/c++ 获取 python 函数的参数数量

问题描述

在 pybind11 中,我有一个类型为 的变量pybind11::function。在 c++ 中,有什么方法可以确定该函数需要多少个参数?即,如果它来自def f(a, b),答案将是 2。我意识到这可能会变得疯狂 w/r *arks、kwargs、self 等......

需要明确的是,这是在 c++ 内部,所以我正在寻找 c++ 代码。

标签: pythonpybind11

解决方案


这是您可以使用的方法inspect.signature()

from inspect import signature

import os # I only imported os to demonstrate with one of its functions

print(signature(os.remove)) # Print out the arguments for the remove fumction from the os module

输出:

(path, *, dir_fd=None)

推荐阅读