clang - 如何在 Clang 中以字符串形式获取函数定义/签名?

标签 clang libclang

假设我有 CXCursor 左右,如何使用 Clang/Libclang 将函数的签名(或至少整个定义?)作为字符串获取?

我认为可以通过使用光标的范围以某种方式获得定义,但我真的不知道如何(使用什么函数)。

最佳答案

您可以使用这个简单的代码来获取函数的原型(prototype)(名称、返回类型、参数计数和参数[名称、数据类型])。

 string Convert(const CXString& s)
{
    string result = clang_getCString(s);
    clang_disposeString(s);
    return result;
}
void print_function_prototype(CXCursor cursor)
{
    // TODO : Print data! 
    auto type = clang_getCursorType(cursor);


    auto function_name = Convert(clang_getCursorSpelling(cursor));
    auto return_type   = Convert(clang_getTypeSpelling(clang_getResultType(type)));

    int num_args = clang_Cursor_getNumArguments(cursor);
    for (int i = 0; i < num_args; ++i)
    {
        auto arg_cursor = clang_Cursor_getArgument(cursor, i);
        auto arg_name = Convert(clang_getCursorSpelling(arg_cursor));
        if (arg_name.empty())
        {
            arg_name = "no name!";
        }

        auto arg_data_type = Convert(clang_getTypeSpelling(clang_getArgType(type, i)));
    }
}
CXChildVisitResult functionVisitor(CXCursor cursor, CXCursor /* parent */, CXClientData /* clientData */)
{
    if (clang_Location_isFromMainFile(clang_getCursorLocation(cursor)) == 0)
        return CXChildVisit_Continue;

    CXCursorKind kind = clang_getCursorKind(cursor);
    if ((kind == CXCursorKind::CXCursor_FunctionDecl || kind == CXCursorKind::CXCursor_CXXMethod || kind == CXCursorKind::CXCursor_FunctionTemplate || \
         kind == CXCursorKind::CXCursor_Constructor))
    {
        print_function_prototype(cursor);
    }

    return CXChildVisit_Continue;
}

关于clang - 如何在 Clang 中以字符串形式获取函数定义/签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45430971/

相关文章:

c - GCC 中 -ffixed-<reg> 标志是否总是有问题?

clang - 运行多个 clang pass

c++ - 链接时 GCC 内存过载

c++ - 如何在VS 2019的Ninja和Clang上添加包含路径?

c++ - 编译时允许的最大警告数

python - 如何使用 libclang 检索完全限定的函数名称?

c++ - 使用 libclang 从内存中的 C 代码生成程序集

c++ - 使用 libclang 检查通用属性

c++ - LLVM cmake安装找不到DIA SDK