clibffi

How to create an `ffi_type` that represents a c array?


typedef struct _StructWithCArray {
  char a[3];
  char b;
} StructWithCArray;

I represent the a[3] as a struct contain three char, but it will fail on iOS i386 simulator.

Anyone has any ideas how to handle this?


Here is a demo to show the bug. You should use a simulator not newer than iPhone 5 to run the BugReport project, and simulator newer than iPhone 5 seems has no problem in this case.


Solution

  • libffi doesn't have a built-in notion of an array type, primarily because there is no way to pass an array to a function in C -- it always decays as a pointer. However, as you've found, this is not ideal, because you may still need to represent an array as an element of a structure. That is, it's an oversight in libffi.

    The workaround for this is to simply add one element to the structure for each element of the array. In your case you would add three char fields. This works in general because an array has the same alignment as its elements.

    The libffi documentation now explicitly mentions this approach.