首页 > 解决方案 > How to retrieve class names and its method names from C++ header using python

问题描述

I am parsing a C++ header file using Clang module in Python. I am trying to list all class names and its member functions.

Here is what I've have tried

I found this under https://stackoverflow.com/a/40328378/6223628

import clang
import clang.cindex as cl
from clang.cindex import CursorKind

def fully_qualified(c):
    if c is None:
        return ''
    elif c.kind == CursorKind.TRANSLATION_UNIT:
        return ''
    else:
        res = fully_qualified(c.semantic_parent)
        if res != '':
            return res + '::' + c.spelling
    return c.spelling

cl.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
idx = clang.cindex.Index.create()
tu = idx.parse('C:/Repository/myproject/myHeader.h', args='-xc++ --std=c++11'.split())
for c in tu.cursor.walk_preorder():
    if c.kind == CursorKind.CALL_EXPR:
        print (fully_qualified(c.referenced))

I am able to retrieve only some of the class names and the rest or the results are from std namespace.

Any other options available?

标签: pythonc++clang

解决方案


从评论中@Predelnik 的提示中,我将其调整CursorKind为 Class_decl 和 CXX_methods 并获得了所需。

import clang
import clang.cindex as cl
from clang.cindex import CursorKind

def fully_qualified(c):
    if c is None:
        return ''
    elif c.kind == CursorKind.TRANSLATION_UNIT:
        return ''
    else:
        res = fully_qualified(c.semantic_parent)
        if res != '': 
            if res.startswith("myWord"):
                return res+"::"+c.spelling
        return c.spelling 

cl.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
idx = clang.cindex.Index.create()
tu = idx.parse('C:/myproject/myHeader.h', args='-xc++ --std=c++11'.split())
for c in tu.cursor.walk_preorder():
    if c.kind == CursorKind.CLASS_DECL:
        print(fully_qualified(c.referenced))
    elif c.kind == CursorKind.CXX_METHOD:
        print(fully_qualified(c.referenced))

推荐阅读