[cffi-devel] Calculating size of C struct .?!

Frank Goenninger fgoenninger at prion.de
Wed May 10 20:15:22 UTC 2006


Am 10.05.2006 um 21:53 schrieb Luís Oliveira:

> On 2006-maj-10, at 17:19, Frank Goenninger wrote:
>> typedef unsigned long	tcflag_t;
>> typedef unsigned char	cc_t;
>> typedef long		speed_t;	/* XXX should be unsigned long */
>>
>> struct termios {
>> 	tcflag_t	c_iflag;	/* input flags */
>> 	tcflag_t	c_oflag;	/* output flags */
>> 	tcflag_t	c_cflag;	/* control flags */
>> 	tcflag_t	c_lflag;	/* local flags */
>> 	cc_t		c_cc[NCCS];	/* control chars */
>> 	speed_t		c_ispeed;	/* input speed */
>> 	speed_t		c_ospeed;	/* output speed */
>> };
> >
>> with NCCS being #define'd to 20.
>
> CFFI> (defctype tcflag :unsigned-long)
> TCFLAG
> CFFI> (defctype cc :unsigned-char)
> CC
> CFFI> (defctype speed :long)
> SPEED
> CFFI> (defcstruct termios
>         (iflag tcflag)
>         (oflag tcflag)
>         (cflag tcflag)
>         (lflag tcflag)
>         (cc cc :count 20)
>         (ispeed speed)
>         (ospeed speed))
> TERMIOS
> CFFI> (foreign-type-size 'termios)
> 44
> CFFI> (foreign-alloc 'termios)
> #.(SB-SYS:INT-SAP #X00600450) ; pointer to 44 newly allocated bytes

Ah - now that you write it ;-) The bit I was missing is the :count  
directive ...


>> I need to allocate space for this struct and therefore want to  
>> know its size ... As I don't need the struct itself I thought  
>> about calculating the size but I figure there's the problem of  
>> getting all the padding to count to the size...
>
> The size depends on the target platform. Different combinations of  
> CPUs/OSs have different rules for struct alignment and different  
> sizes for types, so your best bet is to define the struct anyway.

Yep. And it works. Thanks!!!

Frank




More information about the cffi-devel mailing list