如何使用pycparser在函数声明中查找函数名?

时间:2017-03-25 10:53:13

标签: python c parsing pycparser

我找到了以下示例来搜索特定的函数名称,如malloc,但我想在C源文件的函数声明中找到所有函数名。所以在ReturnCode HashCreate(Hash** hash, unsigned int table_size)的情况下,我正在寻找HashCreate和行号。因为我没有使用Python而且看起来很复杂,我问我该怎么做?

from __future__ import print_function
import sys

sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

class FuncCallVisitor(c_ast.NodeVisitor):
    def __init__(self, funcname):
        self.funcname = funcname

    def visit_FuncCall(self, node):
        if node.name.name == self.funcname:
            print('%s called at %s' % (self.funcname, node.name.coord))


def show_func_calls(filename, funcname):
    ast = parse_file(filename, use_cpp=True,
                     cpp_path='clang',
                     cpp_args=['-E'])
    v = FuncCallVisitor(funcname)
    v.visit(ast)


if __name__ == "__main__":
    if len(sys.argv) > 2:
        filename = sys.argv[1]
        func = sys.argv[2]
    else:
        filename = 'hash.c'
        func = 'malloc'

    show_func_calls(filename, func)

1 个答案:

答案 0 :(得分:1)

func_defs示例完全符合您的要求:

# Using pycparser for printing out all the functions defined in a
# C file.