I am struggling with libffi (Function Foreign Interface library), probably, due to the lack of C experience. I have the following program that calls a function my_func dynamically using libffi:
#include <stdio.h> #include <stdlib.h> #include <ffi.h> unsigned my_func(double a, double b, double *res) { res[0] = a + b; res[1] = a - b; return 0; } int main(int argc, char *argv[]) { ffi_cif cif; ffi_type *arg_types[3] = { &ffi_type_double, &ffi_type_double, &ffi_type_pointer }; ffi_type *rettype = &ffi_type_uint; if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, rettype, arg_types) != FFI_OK) { fprintf(stderr, "ffi_prep_cif is not successful\n"); exit(EXIT_FAILURE); } double a = 3.0; double b = 2.0; double res[2] = {99.0, 15.0}; void *arg_values[3] = { &a, &b, res }; unsigned status; ffi_call(&cif, FFI_FN(my_func), &status, arg_values); printf("Function return status code %u\n", status); printf("Values in res array: \n"); printf("[0] = %f\n", res[0]); printf("[1] = %f\n", res[1]); return 0; } When I debug the program, it seems that all the arg_values are set correctly:
(gdb) p ((double *) arg_values[2])[0] $1 = 99 (gdb) p ((double *) arg_values[2])[1] $2 = 15 You can see above that the arg_values third values is correctly set to the res array.
However, when I am inside the function my_func, the third argument (the res array) becomes NULL:
Breakpoint 2, my_func (a=3, b=2, res=0x0) at test_ffi.c:6 6 res[0] = a + b; I do not really understand what is wrong here. Could somebody explain to me, why this happens and how to fix it? Thank you!
Update
Thanks to the comments by @selbie, the following modified program works (note that we obtain a second pointer to the array res and pass its address to FFI):
#include <stdio.h> #include <stdlib.h> #include <ffi.h> unsigned my_func(double a, double b, double *res) { res[0] = a + b; res[1] = a - b; return 0; } int main(int argc, char *argv[]) { ffi_cif cif; ffi_type *arg_types[3] = { &ffi_type_double, &ffi_type_double, &ffi_type_pointer }; ffi_type *rettype = &ffi_type_uint; if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, rettype, arg_types) != FFI_OK) { fprintf(stderr, "ffi_prep_cif is not successful\n"); exit(EXIT_FAILURE); } double a = 3.0; double b = 2.0; double res[2] = {99.0, 15.0}; double *p_res = res; void *arg_values[3] = { &a, &b, // res &p_res }; unsigned status; ffi_call(&cif, FFI_FN(my_func), &status, arg_values); printf("Function return status code %u\n", status); printf("Values in res array: \n"); printf("[0] = %f\n", res[0]); printf("[1] = %f\n", res[1]); return 0; }
&operation must be used when passing functions as arguments. Although functions decay to pointers as arrays, here it is important to take the address of the function, becauselibffirequires a pointer to a pointer.