2.3.3 Size and Alignment
libffi will set the size and alignment fields of
an ffi_type object for you. It does so using its knowledge of
the ABI.
You might expect that you can simply read these fields for a type that
has been laid out by libffi. However, there are some caveats.
- The size or alignment of some of the built-in types may vary depending
on the chosen ABI.
- The size and alignment of a new structure type will not be set by
libffi until it has been passed to ffi_prep_cif or
ffi_get_struct_offsets.
- A structure type cannot be shared across ABIs. Instead each ABI needs
its own copy of the structure type.
So, before examining these fields, it is safest to pass the
ffi_type object to ffi_prep_cif or
ffi_get_struct_offsets first. This function will do all the
needed setup.
ffi_type *desired_type;
ffi_abi desired_abi;
…
ffi_cif cif;
if (ffi_prep_cif (&cif, desired_abi, 0, desired_type, NULL) == FFI_OK)
{
size_t size = desired_type->size;
unsigned short alignment = desired_type->alignment;
}
libffi also provides a way to get the offsets of the members of
a structure.
- Function: ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets) ¶
Compute the offset of each element of the given structure type.
abi is the ABI to use; this is needed because in some cases the
layout depends on the ABI.
offsets is an out parameter. The caller is responsible for
providing enough space for all the results to be written – one
element per element type in struct_type. If offsets is
NULL, then the type will be laid out but not otherwise
modified. This can be useful for accessing the type’s size or layout,
as mentioned above.
This function returns FFI_OK on success; FFI_BAD_ABI if
abi is invalid; or FFI_BAD_TYPEDEF if struct_type
is invalid in some way. Note that only FFI_STRUCT types are
valid here.