【问题标题】:Introspecting nested ctypes structures内省嵌套的 ctypes 结构
【发布时间】:2015-01-11 17:00:01
【问题描述】:

类似于this 问题,我想从 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))

想法是,如果字段本身具有_fields_ 属性,则它是一个结构,否则为普通字段,因此打印它。递归工作正常,但在第一级之后我得到repr 打印字符串而不是值。例如:

富 = 1 酒吧 = 2 巴兹 = 3 innerFoo = innerBar = innerBaz = quz = 4

我期望的输出是这样的:

富 = 1 酒吧 = 2 巴兹 = 3 innerFoo = 5 内条 = 23 内巴兹 = 56 quz = 4

我的错误是什么?

【问题讨论】:

    标签: python c introspection


    【解决方案1】:

    我发现这个线程非常有用,所以我添加了这个改进的代码来支持数组:

    #
    def print_ctypes_obj(obj, level=0):
    
        delta_indent="    "
        indent=delta_indent*level
    
        # Assess wether the object is an array, a structure or an elementary type
        if issubclass(type(obj), ctypes.Array) :
            print('{}ARRAY {}'.format(indent, obj))
            for obj2 in obj:
                print_ctypes_obj(obj2, level+1)
    
        elif hasattr(obj, '_fields_'):
            print('{}STRUCTURE {}'.format(indent, obj))
            for fdesc in obj._fields_:
                # Get the next field descriptor
                fname = fdesc[0]
                ftype = fdesc[1]
                if len(fdesc)==3:
                    fbitlen = fdesc[2]
                else:
                    fbitlen = 8*ctypes.sizeof(ftype)
                obj2 = getattr(obj, fname)
                print('{}FIELD {} (type={}, bitlen={})'.format(indent+delta_indent, fname, ftype, fbitlen))
                print_ctypes_obj(obj2, level+2)
    
        else:
            print('{}VALUE = {} (type={})'.format(indent, obj, type(obj)))
    

    【讨论】:

      【解决方案2】:

      解决方案非常简单。

      在打印嵌套结构时,我仍然需要将结构作为属性获取,以便 ctypes 发挥它的魔力:

      print_ctypes_obj(getattr(obj, fname), indent+4)
      

      (代码的另一个问题是迭代对的命名;它们应该是fname, ftype 而不是fname, fvalue,这是不正确且具有误导性的)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多