Best way to get the sizeof a structure

46 views
Skip to first unread message

Floris Bruynooghe

unread,
Jan 13, 2014, 12:43:04 PM1/13/14
to pytho...@googlegroups.com
Hi,

I need to call a function with a structure and the size of that structure, with the structure defined as:

typedef struct {
   ...;
   long field_i_care_about;
   ...;
} foo_t;

In C the function call would be like this:

{
    foo_t data;
    the_func(&data, sizeof(data));
}

However with cffi the best I could come up with is doing:

ffi.cdef('const size_t foo_t_size;')
lib = ffi.verify('const size_t foo_t_size = sizeof(foo_t);')
foo = ffi.new('foo_t*')
lib.the_func(foo, lib.foo_t_size)

So my question is whether this really is the best way to address this or is there some better way of doing this?

Thanks,
Floris

Armin Rigo

unread,
Jan 13, 2014, 4:27:41 PM1/13/14
to pytho...@googlegroups.com
Hi Floris,

On Mon, Jan 13, 2014 at 6:43 PM, Floris Bruynooghe
<floris.b...@gmail.com> wrote:
> lib.the_func(foo, lib.foo_t_size)
>
> So my question is whether this really is the best way to address this or is
> there some better way of doing this?

You have ffi.sizeof():

lib.the_func(foo, ffi.sizeof(foo[0])

or:

lib.the_func(foo, ffi.sizeof("foo_t"))


A bientôt,

Armin.

Floris Bruynooghe

unread,
Jan 14, 2014, 6:08:08 AM1/14/14
to pytho...@googlegroups.com, ar...@tunes.org

Thanks!  I tried simply ffi.sizeof(foo) but didn't think of trying the other two.
 

Floris
Reply all
Reply to author
Forward
0 new messages