This is the mail archive of the libffi-discuss@sourceware.org mailing list for the libffi project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Passing function pointer to fcall


On 11/26/2011 7:05 PM, wp1068189-ssc wrote:
Please take a look at this piece of code:
#include<stdio.h>
#include<ffi.h>
#include<stdlib.h>


int msg(void (*a) (char *)) {
     return 23;
     // but this doesn't work :-(
     a("Hi, there !\n");
}

int main(int argc, char ** argv)
     {


ffi_cif cif; ffi_abi abi; ffi_status status; int nargs = 1; ffi_type *rtype =&ffi_type_uint32; ffi_type **atypes; void **avalues; void *result;

     atypes = malloc(sizeof(ffi_type));
     atypes[0] =&ffi_type_pointer;

     avalues = malloc(sizeof(ffi_type_pointer));
     // I want to call msg with a pointer to printf
     *(void**)avalues[0] = printf;

status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, nargs, rtype, atypes);

result = (ffi_type *) malloc(sizeof(rtype->size));

     if(status != FFI_OK)
         printf("ffi_prep_cif failed (%i)\n",status);

ffi_call(&cif,FFI_FN(msg),result,avalues);

return(*(int *)result);
}
As you might imagine, I'd like to call a function "msg" and send it a pointer to
printf,
but that does not work.
I guess it has to do with the pointer me is constructing.
But I have absolutely no idea what I'm doing wrong.
Can anyone help, please ?


Let's get the obvious one of out the way... you are returning from msg() before calling the function.

I'm going to assume that's a typo or something.

What platform are you working on? Also, you should declare "a" in msg() to have the same prototype as printf.

Also, there's an oddity in the libffi API, and that is that "result" needs to be the largest native integral type on your system. So, use a long for result instead of mallocing the exact return type size. You can pass it into ffi_call as &result and simply cast it to an int at the end.

Anthony Green


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]