How to get function definition/signature as a string in Clang?

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

How can I get a function's signature (or at least the entire definition?) as a string using Clang/Libclang, assuming I have its CXCursor or so?

I think that the definition may be somehow obtainable by using the cursor's extents, but I don't really know how (what function to use).

回答1:

You can use this simple code to get prototype of a function ( name, return type, count of arguments and arguments[name,data type]).

 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; }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!