说我分析这样的代码:
df.groupby(..).transform(..)
我使用clang LibTooling并在struct Foo
{
void(*setParam)(const char* name, int value);
};
上获得FieldDecl
。
我认为我可以得到像这样的参数类型:
setParam
但是如何获得参数名称? (在这种情况下,“名称”和“值”)是否有可能?或者我需要手动查看来源(使用auto ft = fieldDecl->getFunctionType()->getAs<FunctionProtoType>();
for (size_t i = 0; i < fpt->getNumParams(); i++)
{
QualType paramType = fpt->getParamType(i);
....
}
)?
答案 0 :(得分:1)
我认为直接从类型中获取参数名称是不可能的,因为它们不是类型信息的一部分。
但是您的任务可以通过再访问一次函数指针声明来完成:
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表示此参数不在嵌套上下文中。