How to set the __str__ method for all ctype structure classes?

[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.)

+3
source share
1 answer

Unfortunately, there is no such way. Attempting to change the class Structureresults 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 to every return structure that you care about which delegates do not override methods for the wrapped structure. Something like that:

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
+1
source

Source: https://habr.com/ru/post/1784441/


All Articles