问题描述
我在某些C代码上使用libclang python绑定。我不知道如何获取有关sizeof
节点的信息。我找不到任何相关文档。实验性地:
-
sizeof
节点的类型为CursorKind.CXX_UNARY_EXPR
。 -
sizeof(type)
没有孩子。sizeof expression
有一个孩子,expression
。
到目前为止,感觉还不错,那又是什么呢?如何将sizeof
与其他一元表达式区分开?如何在sizeof(type)
中获取类型?
我正在使用libclang 10.0.0和Ubuntu 18.04(python3-clang-10
)中随附的相应Python绑定。
这是一个小的C源文件foo.c
,可以尝试:
#include <stddef.h>
size_t foo(void) {
return sizeof(unsigned short) + sizeof 1234;
}
从Clang AST解析器进行的转储显示了我期望的所有信息。
$ clang -Xclang -ast-dump -fsyntax-only foo.c | tail -n 5
`-ReturnStmt 0x97ad48 <line:3:5,col:44>
`-BinaryOperator 0x97ad28 <col:12,col:44> 'unsigned long' '+'
|-UnaryExprOrTypeTraitExpr 0x97acc8 <col:12,col:33> 'unsigned long' sizeof 'unsigned short'
`-UnaryExprOrTypeTraitExpr 0x97ad08 <col:37,col:44> 'unsigned long' sizeof
`-IntegerLiteral 0x97ace8 <col:44> 'int' 1234
这是我用来探索Python数据结构的Python代码。
#!/usr/bin/env python3
import clang.cindex
from clang.cindex import CursorKind
def explore_attrs(node):
for attr in sorted(dir(node)):
try:
value = getattr(node,attr)
except AssertionError as e: # Skip attributes whose accessor only works with specific kinds
continue
if callable(value): continue
if value is None: continue
print(attr,repr(value))
def explore(node):
"""Print information about an AST node."""
print('Children:',[(child.kind,child.spelling) for child in node.get_children()])
print('Arguments:',list(node.get_arguments()))
print('Definition:',node.get_definition())
explore_attrs(node)
def main():
index = clang.cindex.Index.create()
tu = index.parse('foo.c')
for node in tu.cursor.walk_preorder():
if node.kind == CursorKind.RETURN_STMT:
children = list(node.get_children())
# Expect sizeof(...) + sizeof(...)
assert children[0].kind == CursorKind.BINARY_OPERATOR
lhs,rhs = children[0].get_children()
explore(lhs)
print()
explore(rhs)
main()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)