如何使用 clang LibTooling 获取函数指针参数名称
How to get function pointer arguments names using clang LibTooling?
>假设我分析这样的代码:
struct Foo
{
void(*setParam)(const char* name, int value);
};
我使用clang LibTooling并在setParam
上获得FieldDecl
。
我想我可以得到这样的参数类型:
auto ft = fieldDecl->getFunctionType()->getAs<FunctionProtoType>();
for (size_t i = 0; i < fpt->getNumParams(); i++)
{
QualType paramType = fpt->getParamType(i);
....
}
但是如何获取参数名称?(在这种情况下为"名称"和"值")这甚至可能吗,或者我需要手动查看源代码(使用 SourceManager
)?
我认为
不可能直接从类型中获取参数名称,因为它们不是类型信息的一部分。
但是您的任务可以通过再访问一次函数指针声明来完成:
class ParmVisitor
: public RecursiveASTVisitor<ParmVisitor>
{
public:
bool VisitParmVarDecl(ParmVarDecl *d) {
if (d->getFunctionScopeDepth() != 0) return true;
names.push_back(d->getName().str());
return true;
}
std::vector<std::string> names;
};
那么调用站点是:
bool VisitFieldDecl(Decl *d) {
if (!d->getFunctionType()) {
// not a function pointer
return true;
}
ParmVisitor pv;
pv.TraverseDecl(d);
auto names = std::move(pv.names);
// now you get the parameter names...
return true;
}
注意getFunctionScopeDepth()
部分,这是必要的,因为函数参数本身可能是函数指针,如下所示:
void(*setParam)(const char* name, int value, void(*evil)(int evil_name, int evil_value));
getFunctionScopeDepth()
为 0 可确保此参数不在嵌套上下文中。
相关文章:
- 为函数定义符号不明确的指针参数
- 构造函数 (C++) 中的 char 指针参数存在问题
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么具有指针参数的成员函数需要指向指针的指针?
- 通过引用函数传递指针参数是什么意思?
- 从double到double*的指针参数
- void 函数中的指针参数返回不一致的值
- 无法向上转换指针到指针参数
- 将数组动态分配到具有指针参数的函数中
- 模板函数指针参数与构造函数参数
- 使用通用函数指针参数化函数模板的简洁方法
- 如何为C++字符串分配空指针参数?
- C++带有指针参数的函数
- 指针参数的默认值
- 将常量添加到函数模板指针参数
- 如何传递unique_ptr<T>代替原始*输出*指针参数?
- 不带星号的函数指针参数
- 功能指针参数参数转换为const
- 将指针参数传递给双指针参数
- 如何调试指针参数是否通过函数修改