How to set a __str__ method for all ctype Structure classes?
[Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.]
I just wrote a __str__
met开发者_JAVA技巧hod for a ctype-generated Structure class 'foo' thus:
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 fairly natural way to produce a __str__
method for any Structure class. How can I add this method directly to the Structure class, so that all Structure classes generated by ctypes get it?
(I am using the h2xml and xml2py scripts to auto-generate ctypes code, and this offers no obvious way to change the names of the classes output, so simply subclassing Structure, Union &c. and adding my __str__
method there would involve post-processing the output of xml2py.)
Unfortunately there is no such way. Attempting to modify the Structure
class itself results in
TypeError: can't set attributes of built-in/extension type '_ctypes.Structure'
The closest you can get is a wrapper class that you apply yourself to each return Structure you care about which delegates non overridden methods to the wrapped Structure. Something like this:
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
精彩评论