Storable tuples and what is 'alignment'?
Simon Marlow
simonmar at microsoft.com
Tue Aug 6 04:47:45 EDT 2002
[ moved to ffi at haskell.org ]
> You also need to allow for any padding which is required to satisfy
> the alignment constraints of b, e.g.
>
> sizeOf (a,b) = sizeOf a + padding (a,b) + sizeOf b
> where padding (a,b) = (alignment b - sizeOf a
> `mod` alignment b) `mod` alignment b
>
> > alignment (a,b) = alignment a + alignment b
>
> The alignment of the overall structure is determined by the alignment
> of the first element. Subsequent elements are aligned (if necessary)
> by the addition of padding between elements.
>
> alignment (a,_) = alignment a
I think in fact that the aligment of the whole structure should be
alignment (a,b) = alignment a `max` aligment b
which would mean that sizeOf should be defined as
sizeOf (a,b) = sizeOf a + padding + sizeOf b
where b_align = alignment b
padding = case sizeOf a `mod` b_align of
0 -> 0
n -> b_align - n
consider for example
struct { int a; double b }
on a 32-bit architecture where doubles must be aligned on an 8-byte
boundary (eg. Sparc), gcc will always align the structure on an 8-byte
boundary and put 4 bytes of padding between the elements.
Cheers,
Simon
More information about the FFI
mailing list