我有一个简单的 C 程序test.c
,我想在 pycparser 的帮助下获取sample_enum
和sample_struct
使用 python 的成员。
#include <stdio.h>
typedef enum sample_enum
{
board1 = 0,
board2 = 1,
board3 = 2,
board4 = 3,
board5 = 4,
board6 = 5,
} sample_enum_t;
typedef struct sample_struct {
uint32_t pd_type1;
uint32_t pd_type2;
uint32_t pd_type3;
} sample_struct_t;
int main() {
return 0;
}
我得到预处理输出并将其保存到test.txt
.
gcc -E -I/path/to/pycparser/utils/fake_libc_include test.c > test.txt
这是我的python程序:
from pycparser import parse_file, c_parser, c_ast
if __name__ == "__main__":
ast = parse_file(filename='test.txt')
ast.show(showcoord=True)
ast.show 打印一堆输出,包括这些:
Typedef: sample_enum_t, [], ['typedef'] (at test.c:11:3)
TypeDecl: sample_enum_t, [] (at test.c:11:3)
Enum: sample_enum (at test.c:3:9)
EnumeratorList: (at test.c:5:5)
Enumerator: board1 (at test.c:5:5)
Constant: int, 0 (at test.c:5:14)
Enumerator: board2 (at test.c:6:5)
Constant: int, 1 (at test.c:6:14)
Enumerator: board3 (at test.c:7:5)
Constant: int, 2 (at test.c:7:14)
Enumerator: board4 (at test.c:8:5)
Constant: int, 3 (at test.c:8:14)
Enumerator: board5 (at test.c:9:5)
Constant: int, 4 (at test.c:9:14)
Enumerator: board6 (at test.c:10:5)
Constant: int, 5 (at test.c:10:14)
Typedef: sample_struct_t, [], ['typedef'] (at test.c:17:3)
TypeDecl: sample_struct_t, [] (at test.c:17:3)
Struct: sample_struct (at test.c:13:16)
Decl: pd_type1, [], [], [] (at test.c:14:14)
TypeDecl: pd_type1, [] (at test.c:14:14)
IdentifierType: ['uint32_t'] (at test.c:14:5)
Decl: pd_type2, [], [], [] (at test.c:15:14)
TypeDecl: pd_type2, [] (at test.c:15:14)
IdentifierType: ['uint32_t'] (at test.c:15:5)
Decl: pd_type3, [], [], [] (at test.c:16:14)
TypeDecl: pd_type3, [] (at test.c:16:14)
IdentifierType: ['uint32_t'] (at test.c:16:5)
FuncDef: (at test.c:20:5)
Decl: main, [], [], [] (at test.c:20:5)
FuncDecl: (at test.c:20:5)
TypeDecl: main, [] (at test.c:20:5)
IdentifierType: ['int'] (at test.c:20:1)
Compound: (at test.c:20:1)
Return: (at test.c:22:5)
Constant: int, 0 (at test.c:22:12)
所以我的问题是,我是否需要解析输出并分别提取 enum 和 struct 的成员?或者里面有一个内置的方法/机制pycparser
可能会让我的生活更轻松。