Thanks for such a great tool. CFFI really is a bit of magic.
I've been working on wrapping a C-based device communication SDK for a short while. I've figured out everything I need from the CFFI documentation and examples—except for one troublesome problem.
The SDK I'm wrapping is for interacting with a USB-connected proprietary device. One dataset the device communicates over the wire includes some byte padding for certain members of a memory block. I do not know exactly why the padding exists, nor am I able to change it. The device SDK handles the padding with struct-embedded nameless unions that encompass two items, the desired element and a “throwaway” array of 8 unsigned chars that provides the padding.
No matter what I've tried, I cannot find a resolution to this sort of error:
ffi.error: <struct name>: wrong size for field '<field>' (cdef says 4, but C compiler says 8). fix it or use "...;" as the last field in the cdef…
Here is a representative version of the troublesome struct/union in the SDK:
// SDK header file
typedef struct
{
union
{
SOURCE_t source; // An enum
unsigned char padding1[8];
};
union
{
time_t time;
unsigned char padding2[8];
};
char some_data[512];
char more_data[64];
char another_array_field[64];
short simple_field;
} SDK_DATA_t;
I've tried variations / permutations of:
- Adding ...; as the final field of the unions in the CDEF.
- Adding ...; as the final field of the containing struct in the CDEF.
- Omitting the padding character arrays of the unions in the CDEF.
- Naming the union in the source header file and CDEF.
- Extracting dedicated typedefs for the unions and using them within the structs in the source header file and CDEF.
Nothing has worked so far. And, I'd like to avoid modifying the SDK header file (some of my experiments have modified the header file).
How do I help CFFI figure out that the field within the union is a simple type but that there's possible padding bytes to ignore? I'm guessing CFFI is more than capable at handling this, but I've not found the secret sauce.
Any guidance or troubleshooting is much appreciated!