¿Usando __repr__() en una subclase de ctypes?

I am playing around with ctypes a little bit to massage some C code I wrote into Python. The C code relies heavily on structs and unions, and for now, the quick solution in Python is to subclass those via ctypes:

I.e., from this:

struct foo {
    uint32_t a;
    uint32_t b;
    uint16_t c;
    uint16_t d;
};


A esto:

from ctypes import *

class Foo(Structure):
    _fields_ = [("a", c_uint),
                ("b", c_uint),
                ("c", c_ushort),
                ("d", c_ushort)]

Except, if I toss a __repr__() definition into the Python class and then use repr() on an instance, all I get back is <class 'Foo'> (or something to that effect, recalling from memory a bit here).

So I am wondering if there is a way to utilize repr() and try to get the best of both worlds between Python and C, or if I should look at metaclasses and using the struct library for packing/unpacking bytes into proper Python classes.

Pensamientos

preguntado el 22 de mayo de 12 a las 20:05

1 Respuestas

I don't really understand the problem. This works just fine:

from ctypes import *

class Foo(Structure):
    _fields_ = [("a", c_uint),
                ("b", c_uint),
                ("c", c_ushort),
                ("d", c_ushort)]

    def __repr__(self):
        return "<Foo: a:%d b:%d c:%d e:%d>" % (self.a, self.b, self.c, self.d)

f = Foo(1,2,3,4)
print repr(f)

# <Foo: a:1 b:2 c:3 e:4>

only if you do:

print repr(Foo)

terminarás con

<class '__main__.Foo'>

o algo similar.

Are your sure you use repr on an instance?

contestado el 22 de mayo de 12 a las 21:05

Well, I am doing this on Python 2.4, after manually building ctypes for it. Might that be part of the problem? - Kumba

Somehow I find that unlikely, I just tried it on a server with python2.4 and it worked. - mata

Okay, chalk this one up to PEBKAC or PICNIC. I was doing f=FooNO f=Foo(). Herp derp. - Kumba

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.