如何为所有ctype结构类设置__str__方法?

4 投票
1 回答
1020 浏览
提问于 2025-04-16 09:41

自从我问这个问题后,我发现了一个很好的答案,地址是:http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/

我刚为一个用ctype生成的结构类'foo'写了一个__str__方法,代码如下:

def foo_to_str(self):
  s = []
  for i in foo._fields_:
    s.append('{}: {}'.format(i[0], foo.__getattribute__(self, i[0])))
  return '\n'.join(s)

foo.__str__ = foo_to_str

不过,这种方式其实是为任何结构类生成__str__方法的一个很自然的做法。我想知道怎么才能把这个方法直接加到结构类上,这样所有用ctypes生成的结构类都能用上这个方法?

(我正在使用h2xml和xml2py这两个脚本来自动生成ctypes代码,而这些脚本没有明显的方法来改变输出类的名称,所以如果我只是简单地继承结构类、联合类等,然后在那儿添加我的__str__方法,就需要在xml2py的输出结果上进行后处理。)

1 个回答

1

很遗憾,没有这样的办法。试图直接修改 Structure 这个类会导致

TypeError: can't set attributes of built-in/extension type '_ctypes.Structure'

你能做到的最接近的方式是创建一个包装类,这个类可以应用到你关心的每个返回的 Structure 上。这个包装类会把那些没有被重写的方法转发给被包装的 Structure。大概是这样的:

class StructureWrapper(object):
    def __init__(self, structure):
        self._ctypes_structure = structure
    def __getattr__(self, name):
        return getattr(self._ctypes_structure, name)
    def __str__(self):
        # interesting code here

撰写回答