【发布时间】:2017-11-05 03:07:03
【问题描述】:
pycparser 是否支持用户定义类型?我想从 *.C 文件中获取用户定义类型作为返回类型的函数列表。
【问题讨论】:
标签: python c parsing pycparser
pycparser 是否支持用户定义类型?我想从 *.C 文件中获取用户定义类型作为返回类型的函数列表。
【问题讨论】:
标签: python c parsing pycparser
确实如此。您只想为FuncDef 节点写一个访问者。
FuncDef 包含一个Decl,其子类型为FuncDecl。
这个FuncDecl 将返回类型作为其子类型。
返回类型是TypeDecl,在这种情况下是类型标识符
是它的子类型,或者是PtrDecl,在这种情况下,它的子类型是TypeDecl,其子类型是类型标识符。
明白了吗?下面是一个示例 FuncDef visitor,它打印每个函数的名称和返回类型:
class FuncDefVisitor(c_ast.NodeVisitor):
"""
A simple visitor for FuncDef nodes that prints the names and
return types of definitions.
"""
def visit_FuncDef(self, node):
return_type = node.decl.type.type
if type(return_type) == c_ast.TypeDecl:
identifier = return_type.type
else: # type(return_type) == c_ast.PtrDecl
identifier = return_type.type.type
print("{}: {}".format(node.decl.name, identifier.names))
这是解析 cparser 分发中的 hash.c 示例文件时的输出:
hash_func: ['unsigned', 'int']
HashCreate: ['ReturnCode']
HashInsert: ['ReturnCode']
HashFind: ['Entry']
HashRemove: ['ReturnCode']
HashPrint: ['void']
HashDestroy: ['void']
现在您只需过滤掉内置类型,或过滤出您感兴趣的 UDT。
【讨论】: