ctypes module, question on Arrays

Alex Martelli aleax at aleax.it
Wed Mar 19 03:50:02 EST 2003


Josh wrote:

> Hi,
> 
> I have been trying to design a class which is inherited from the Array
> class in the ctypes module. Surprisingly, I cannot set the length of the
> array at runtime:

Sure you can -- "runtime" is when the class statement executes, of course.
You can and MUST set _length_ (and _type_) class attributes when the
class statement executes.

> The only solution seems to be to set the _length_ in the class
> definition at design time like so:

Not sure what you mean by "design time".  Everything is determined when
the class statement runs -- that instantiates the class object.


> instantiating? What's going on? And how can I set the length of the array
> at runtime?

myarray = (c_double * 10)()

for example -- the multiplication defines an Array subclass of length 10
and type c_double on the fly, then the () calls the class and therefore
gives you the instance.  In place of that "10" use any int > 0, of course.

Wrapping this into a factory function is just as easy, of course:

def Darray(length=10, type=c_double):
    return (type*length)()


Alex
        




More information about the Python-list mailing list