Re: [ctypes-users] Can't create small bitfields
Brought to you by:
theller
From: Rob G. <rg...@hi...> - 2014-04-16 17:16:54
|
On Tue, 15 Apr 2014 22:54:45 -0400 eryksun <er...@gm...> wrote: > On Tue, Apr 15, 2014 at 8:01 PM, Rob Gaddi > <rg...@hi...> wrote: > > the smallest Structure I can get is 4 bytes. Any ideas on what I'm > > doing wrong? > > > > from __future__ import print_function > > from ctypes import * > > > > class Struct(Structure): > > _pack_ = 1 > > > > Struct._fields_ = [ > > ('low', c_uint, 4), > > ('high', c_uint, 4), > > ] > > You're using c_uint as the storage unit size. Instead use c_ubyte: > > from ctypes import * > > class Struct(Structure): > _fields_ = [('low', c_ubyte, 4), > ('high', c_ubyte, 4)] > > x = Struct(low=7, high=15) > > > >>> sizeof(x) > 1 > >>> (x.high << 4) + x.low > 247 > >>> list(bytes(x)) > [247] Eryksun -- Thanks, that fixed the immediate problem. Though it did help point out the degree to which I really don't understand what makes Structure bitfields work. For instance, I would have expected that if I took the above, and made each field a c_uint8 of size 6, that I'd get a two byte structure with 'high' spanning the byte boundary. But in order to get that, I need to use c_uint16 as the underlying type instead; c_uint8s give me two bits of padding between. So, is the underlying type size supposed to match the size of the overall structure you're trying to fill? Is there any simple reference on this, or is it just a matter of sitting down with a solid 4 hours to burn to read the _ctypes code? Thanks again, Rob -- Rob Gaddi, Highland Technology 18 Otis St. San Francisco, CA 94103 415-551-1700 |