Tam*_*lei 4 c python introspection
与此问题类似,我想从 Python 打印 C 结构的成员。
我实现了以下功能:
def print_ctypes_obj(obj, indent=0):
for fname, fvalue in obj._fields_:
if hasattr(fvalue, '_fields_'):
print_ctypes_obj(fvalue, indent+4)
else:
print '{}{} = {}'.format(' '*indent, fname, getattr(obj, fname))
Run Code Online (Sandbox Code Playgroud)
这个想法是,如果字段本身有一个_fields_属性,那么它是一个结构,否则是一个普通的字段,所以打印它。递归工作正常,但在第一级之后,我repr打印的是字符串而不是值。例如:
富 = 1
条 = 2
巴兹 = 3
innerFoo = <字段类型=c_long, ofs=0, size=4>
innerBar = <字段类型=c_long, ofs=4, size=4>
innerBaz = <字段类型=c_long, ofs=8, size=4>
测验 = 4
我期望的输出类似于:
富 = 1
条 = 2
巴兹 = 3
内富 = 5
内栏 = 23
内巴兹 = 56
测验 = 4
我在这里有什么错误?
解决方案非常简单。
打印嵌套结构时,我仍然需要将结构作为属性获取,以便 ctypes 可以发挥其魔力:
print_ctypes_obj(getattr(obj, fname), indent+4)
Run Code Online (Sandbox Code Playgroud)
(代码的另一个问题是迭代对的命名;它们应该是不正确和误导性fname, ftype的fname, fvalue,而不是哪个)