Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created September 27, 2012 23:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TooTallNate/3797011 to your computer and use it in GitHub Desktop.
Save TooTallNate/3797011 to your computer and use it in GitHub Desktop.
how to define a "ffi_type" for a struct with inlined arrays for libffi
#include <stdio.h>
#include <ffi/ffi.h>
/* The struct with inlined arrays */
struct test {
int array[5];
char str[6];
};
/* The function to FFI invoke */
struct test fn (struct test test, int input) {
int i;
for (i = 0; i < 5; i++) {
printf("test.array[%d]: %d\n", i, test.array[i]);
}
printf("test.str as string: %s\n", &test.str[0]);
printf("int input: %d\n", input);
return test;
}
int main () {
ffi_cif cif;
ffi_type test_struct_type;
ffi_type *arg_types[2];
void *arg_values[2];
ffi_status status;
struct test result;
struct test arg;
int input;
// create the "test_struct_type" `ffi_type`
test_struct_type.size = 0;
test_struct_type.alignment = 0;
test_struct_type.type = FFI_TYPE_STRUCT;
ffi_type *test_elements[] = {
&ffi_type_sint32,
&ffi_type_sint32,
&ffi_type_sint32,
&ffi_type_sint32,
&ffi_type_sint32,
&ffi_type_uint8,
&ffi_type_uint8,
&ffi_type_uint8,
&ffi_type_uint8,
&ffi_type_uint8,
&ffi_type_uint8,
NULL
};
test_struct_type.elements = test_elements;
printf("number of test.elements: %d\n", (int)(sizeof(test_elements) / sizeof(ffi_type *)));
// populate argument fields
arg.array[0] = 1;
arg.array[1] = 2;
arg.array[2] = 4;
arg.array[3] = 8;
arg.array[4] = 16;
arg.str[0] = 'H';
arg.str[1] = 'e';
arg.str[2] = 'l';
arg.str[3] = 'l';
arg.str[4] = 'o';
arg.str[5] = '\0';
input = 69;
// specify the "ffi_type *" to use for each argument
arg_types[0] = &test_struct_type;
arg_types[1] = &ffi_type_sint32;
// Prepare the ffi_cif structure.
printf("before prep_cif()\n");
status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &test_struct_type, arg_types);
printf("after prep_cif()\n");
if (status != FFI_OK) {
// Handle the ffi_status error.
}
arg_values[0] = &arg;
arg_values[1] = &input;
// Invoke the function.
ffi_call(&cif, FFI_FN(fn), &result, arg_values);
int i;
for (i = 0; i < 5; i++) {
printf("result.array[%d]: %d\n", i, result.array[i]);
}
printf("result.str as string: %s\n", &result.str[0]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment