【问题标题】:How to get function pointer arguments names using clang LibTooling?如何使用 clang LibTooling 获取函数指针参数名称?
【发布时间】:2018-12-24 08:25:41
【问题描述】:

假设我分析这样的代码:

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)?

【问题讨论】:

    标签: c++ clang llvm libtooling


    【解决方案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 确保此参数不在嵌套上下文中。

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 1970-01-01
      • 2023-03-15
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多