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

From: Eli Barzilay (eli at barzilay.org)
Date: Sat Nov 10 20:31:46 EST 2007

On Nov 10, Brian Chin wrote:
> 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.

cstructs types are created directly using libffi, which takes care of
the necessary magic.  As you've discovered, the tricky bit is getting
both the sizeof and alignof right -- if all you care about is the
size, then it might be possible to choose some of the union's fields
as a base type (but being careful with the exact meaning of sizeof, as
Hendrik pointed out).  But things become much more complicated when
alignment is considered too.  Here's a somewhat shorter example that
should be clearer -- given these two definitions:

  union foo1 { char c[5]; } u1;
  union foo2 { char c[5]; int i; } u2;

and run this code:

  int main(int argc, char* argv[]) {
    printf( "foo1: %d %d\n", sizeof(u1), __alignof(u1) );
    printf( "foo2: %d %d\n", sizeof(u2), __alignof(u2) );
    return 0;
  }

then I get

  foo1: 5 1
  foo2: 8 4

Note that in the second one, the alignof comes from the
biggest-alignment field (int i), but the sizeof comes from the
biggest-size field (after applying the alignment).  In this case it
will not be possible to find a field of the union with the right
size/alignment -- but perhaps it will be possible to invent one...
Still, this requires knowing how the C compiler decides to set the
alignment and size of the union, and I'm not even sure that there are
any standards for that.

And finally, even if you do all that, the result would be a bad hack
(inventing a base ctype with the right size/alignment), and a proper
solution is to add union types to libffi, where there should be some
mechanism to compute the right size+alignment information.

(BTW, in the foreign interface, the two functions are called
`ctype-sizeof' and `ctype-alignof', in case you want to play with it.)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.