q66 / cffi-lua

A portable C FFI for Lua 5.1+
MIT License
176 stars 24 forks source link

Fix struct and union array fields #18

Closed vsergeev closed 3 years ago

vsergeev commented 3 years ago
fix fixed size array fields in structs and unions

for a struct like:

struct foo {
    uint32_t x;
    uint8_t y[4];
};

c_record::set_fields() was populating the ffi_type.elements with [uint32_t, uint8_t *], which gives an incorrect structure size of 16 (4 bytes for uint32_t, 4 bytes for padding, 8 bytes for uint_t *) after being prepared by ffi_prep_cif().

this commit modifies c_record::set_fields() to expand fixed size array types into separate elements in ffi_type.elements, e.g. [uint32_t, uint8_t, uint8_t, uint8_t, uint8_t], as described in "2.3.4.1 Arrays" of the libffi documentation, so libffi can correctly calculate the padding and size in ffi_prep_cif().

it also updates the union size logic to use the total size of a fixed size array field instead of the size of a pointer to the array base type.

factor out struct and union fields assignment

this commit factors out the common ffi_type.elements assignment logic from the union and struct code paths in c_record::set_fields().

q66 commented 3 years ago

alright, looks good, thanks