[cffi-devel] foreign-type-size of struct types

James Bielman jamesjb at jamesjb.com
Fri Aug 5 08:02:14 UTC 2005


Wilco Greven <greven at kde.org> writes:

> The example I gave was rather bad. Let me give a better one.
>
> typedef struct {
>   int a;
>   short b;
> } TestStruct;
>
> (defcstruct test-struct
>   (a :int)
>   (e :short))
>
> The problem arose when I wanted to access elements in an array of structs. Say 
> I have an array "TestStruct *tests". I expected to be able to access the 
> individual elements of this array by
>
> (inc-ptr tests (* (foreign-struct-size 'test-struct) array-index)
>
> The problem is that (foreign-type-size 'test-struct) returns a size of 6, 
> while sizeof(TestStruct) returns 8. Therefore the code above doesn't work 
> correctly.
>
> My guess was that this had something to do with alignment of the struct, but I 
> have to admit that my knowledge about memory alignment is pretty much nil. 
> zero.

Indeed this is a bug, but I probably won't have time to look at it for
a little while...

Probably foreign structure types need to sum the alignment of each
member to calculate the total alignment of the structure (and I think
there are some wrinkles with double float alignment on Darwin also).

James



More information about the cffi-devel mailing list