Iterable Ctypes Struct

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 11 17:09:20 EST 2009


En Wed, 11 Feb 2009 16:32:41 -0200, <mark.seagoe at gmail.com> escribió:
> On Feb 11, 9:01 am, mark.sea... at gmail.com wrote:
>> On Feb 10, 9:52 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
>> wrote:
>> > En Wed, 11 Feb 2009 00:31:26 -0200, <mark.sea... at gmail.com> escribió:
>>
>> > > I like the ability to access elements of a struct such as with > >  
>> ctypes
>> > > Structure:
>> > > What I don't like about it is that it's not iterable:
>> > > I don't want to force the end user to have preknowledge of the > >  
>> element
>> > > names.

[recipe using _fields_]

>> Thanks very much, Gabriel.  This is very good start for me.
>> This works for predefined class.  How about a situation where the
>> fields are added dynamically (as from reading in from an xml file).
> I tinkered with it and think I have viable solution.
> I need to append a new member to _fields_ before writing it,
> then it seems to work.
>
>>>> p._fields_.append(('z', c_int))
>>>> point.z = 30
>>>> print 'List:', list(p)
> List: [10, 20, 30]

Yes, that's the way to add a new field -- but you have to do that before
creating the first instance. Anywy, this is somewhat strange for a ctypes
Structure. Usually its memory layout is fixed and mandated by the
library/format/whatever you're trying to bind to.
You are not using it as a generic attribute container, are you? There are
better alternatives in that case.

-- 
Gabriel Genellina




More information about the Python-list mailing list