简体   繁体   English

pybind11:从 c/c++ 获取 arguments 到 python function 的编号

[英]pybind11: from c/c++ get number of arguments to python function

In pybind11, I have a variable of type pybind11::function .在 pybind11 中,我有一个pybind11::function类型的变量。 Is there any way to determine how many arguments that function takes, in c++?有什么方法可以确定 c++ 中 function 需要多少 arguments? Ie if it comes from def f(a, b) , the answer would be 2. I realize this might get crazy w/r *arks, kwargs, self, etc...即,如果它来自def f(a, b) ,答案将是 2。我意识到这可能会变得疯狂 w/r *arks、kwargs、self 等......

To be clear, this is inside of c++, so I'm looking for c++ code.需要明确的是,这是在 c++ 内部,所以我正在寻找 c++ 代码。

Here is how you can use inspect.signature() :以下是如何使用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

Output: Output:

(path, *, dir_fd=None)

So here's how to do this in pybind11:所以这里是如何在 pybind11 中做到这一点:

#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
pybind11::function callback_; // from somewhere!
pybind11::module inspect_module = pybind11::module::import("inspect");
pybind11::object result = inspect_module.attr("signature")(callback_).attr("parameters");
auto num_params = pybind11::len(result);
// num_params is an int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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