[Asking this question, I found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ , which gives a good answer.]
I just wrote a method __str__for the ctype-generated structure class 'foo' in this way:
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
But this is a pretty natural way to create a method __str__for any Structure class. How can I add this method directly to the Structure class so that all its structure classes created by ctypes get it?
(I use h2xml and xml2py scripts to automatically generate ctypes code, and this does not provide an obvious way to change the class output names, so just subclass Structure, Union & c and adding my __str__method will include post-processing of xml2py output.)
source
share