[plt-scheme] "define-cunion" prototype for FFI

From: Brian Chin (naerbnic at ucla.edu)
Date: Sat Nov 10 17:18:10 EST 2007

Hmmm, apparently I was mistaken with how make-cstruct-type worked in  
the first place. I suppose I'm back to the drawing board for a little  
while I do some research. Thanks for the info.

- Brian Chin
On Nov 10, 2007, at 1:59 PM, Jon Rafkind wrote:

> Brian Chin wrote:
>>
>> On Nov 10, 2007, at 12:07 PM, hendrik at topoi.pooq.com wrote:
>>
>>> On Sat, Nov 10, 2007 at 11:01:11AM -0800, Brian Chin wrote:
>>>>
>>>> Correct me if my understanding is flawed, but unions are notably
>>>> simpler than structs, given that most of the alignment issues  
>>>> can be
>>>> avoided since all of the "fields" have a pointer offset of 0. In  
>>>> that
>>>> regard, the only remaining issues is ensuring that the union  
>>>> type has
>>>> the correct size, which should be the maximum size of it's members.
>>>
>>> in C, the sizeof() of a type is not the number of bytes it takes  
>>> but the
>>> spacing between adjacent elements if it is packed into an array.   
>>> This
>>> may be different from the actual size of a value of that type.--
>>
>> Ah, excellent point. Instead of just using the raw type, I create  
>> as a
>> new basetype a struct type with a single element (via
>> make-cstruct-type), which should solve those alignment issues, unless
>> there's a platform where the type with the largest sizeof will not
>> have the largest aligned size.
>>
> It doesn't seem to match gcc.
> (define bytes (make-cstruct-type (ctypes _byte 9)))
>
> (define-cstruct _Foo
>         ((y bytes)))
>
> (define-cunion _X1
>            ((z _pointer)
>         (x _int)
>         (y _Foo)))
>
> Size of _X1 is 9, but gcc would say 16. I'm not sure what the rules  
> are
> for determining the size of a union but gcc does some wierd things
> sometimes.
>
> union y{
>     struct{
>         int x;
>         int q;
>     };
>     struct{
>         char x;
>         void * p;
>     };
>     int q;
> };
> is 16 bytes but
>
> union y{
>     struct{
>         int x;
>         int q;
>     };
>     struct{
>         char x;
>         short f;
>         short q;
>         short p;
>         short n;
>      };
>     int q;
> };
>
> is 12 bytes on a 64-bit machine.
>> For those who are curious about the code, I've posted my version of
>> foreign.ss here. All of the changes are near the definition to
>> define-cstruct and define-cunion:
>>
> You forgot to provide define-cunion ;)
>> http://www.cs.ucla.edu/~naerbnic/foreign.ss
>>
>> Have fun!
>> - Brian Chin
>>
>>
>> _________________________________________________
>>  For list-related administrative tasks:
>>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>>
>>
>



Posted on the users mailing list.