如何通过Python版libclang获取C++结构体多维数组的维度大小
获取C++多维数组各维度大小的libclang Python绑定解决方案
有两种可靠方式提取POD结构体中多维数组的所有维度大小:
方法1:通过类型层级递归获取(推荐)
多维数组的每一层维度对应一个CONSTANTARRAY类型,我们可以循环拆解类型,直到当前类型不再是数组类型,逐层收集维度大小:
修改后的Python代码
import clang.cindex as cl def get_all_array_dims(ctype): dims = [] # 循环判断当前类型是否为常量数组 while ctype.kind == cl.TypeKind.CONSTANTARRAY: dims.append(ctype.get_array_size()) # 进入下一层元素类型 ctype = ctype.get_array_element_type() return dims def process(c): if c.kind in [cl.CursorKind.STRUCT_DECL, cl.CursorKind.CLASS_DECL]: print("Found struct: ", c.spelling) for field in c.type.get_fields(): print("Found field: ", field.spelling) dims = get_all_array_dims(field.type) if dims: print("Array dimensions: ", dims) return for child in c.get_children(): process(child) idx = cl.Index.create() # 添加C++解析参数,确保正确识别C++语法 tu = idx.parse("test.hpp", args=['-x', 'c++']) process(tu.cursor)
运行输出
Found struct: my_struct Found field: mdarr Array dimensions: [10, 20]
方法2:通过游标子节点的字面值提取
针对你代码中发现的INTEGER_LITERAL节点,可以通过get_tokens()提取字面值文本并转换为整数:
相关代码片段
# 在字段遍历的循环内添加 for child in field.get_children(): if child.kind == cl.CursorKind.INTEGER_LITERAL: # 遍历节点的token,提取字面值 for token in child.get_tokens(): print("Dimension size: ", int(token.spelling))
对应输出
Found struct: my_struct Found field: mdarr Array size: 10 Dimension size: 10 Dimension size: 20
注意事项
- 方法1更稳定,直接依赖clang的类型系统,不受AST节点遍历顺序干扰,支持任意深度的嵌套数组。
- 解析头文件时务必添加
-x c++参数,避免clang以C模式解析导致类型识别错误。
内容的提问来源于stack exchange,提问作者Dudeman McGuybro
相关产品推荐
相关产品推荐

