pycparser 是否支持用户自定义类型?我想从 *.C 文件中获取用户定义类型作为返回类型的函数列表。
最佳答案
当然可以。您只想为 FuncDef
节点编写访问者。
FuncDef
包含一个Decl
,其子类型是一个FuncDecl
。
此 FuncDecl
将返回类型作为其子类型。
返回类型是TypeDecl
,在这种情况下是类型标识符
是它的子类型,或者它是一个 PtrDecl
,在这种情况下,它的子类型是 TypeDecl
,它的子类型是类型标识符。
明白了吗?下面是一个打印每个函数的名称和返回类型的 FuncDef
访问器示例:
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。
关于python - pycparser 是否支持用户定义的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47117781/