This is the mail archive of the
libffi-discuss@sourceware.org
mailing list for the libffi project.
RE: Function pointers?
- From: Nathan Rossi <nathan dot rossi at xilinx dot com>
- To: The Devils Jester <thedevilsjester at gmail dot com>, "libffi-discuss at sourceware dot org" <libffi-discuss at sourceware dot org>
- Date: Tue, 5 Mar 2013 07:46:53 +0000
- Subject: RE: Function pointers?
- References: <CAP9jBPi4zifMTUP_U972a2qeHtp_=-srpdVQpOnGQrifE2qg2Q@mail.gmail.com>
> -----Original Message-----
> From: libffi-discuss-owner@sourceware.org [mailto:libffi-discuss-
> owner@sourceware.org] On Behalf Of The Devils Jester
> Sent: Tuesday, March 05, 2013 4:06 PM
> To: libffi-discuss@sourceware.org
> Subject: Function pointers?
>
> I can pass pointers as arguments to a function without issue unless it
> is a function pointer. When I try and pass a function pointer, it
> gets jumbled during the pass. What am I doing wrong?
>
> Here is an example code that prints the value of the pointer before
> its passed, and in the function its passed to. Both values are
> different, does anyone know why?
>
> (I am running OS X 10.8.2)
>
> #include <stdio.h>
> #include <ffi.h>
>
> int test_a(void*ptr)
> { return 0; }
>
> int test_b(void*ptr)
> {
> printf("Address of passed ptr: %p\n", ptr );
> return 0;
> }
>
> int main()
> {
> ffi_cif cif;
> ffi_type *args[1];
> void *values[1];
> int rc;
>
> args[0] = &ffi_type_pointer;
> values[0] = &test_a;
>
> if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_uint, args) == FFI_OK)
> {
> printf("Address of ptr to pass: %p\n", values[0] );
> ffi_call(&cif, test_b, &rc, values);
> }
> return 0;
> }
Hi,
The 'values' array you are passing to ffi_call needs to contain pointers to the associated data (in this case the data is the function pointer). Because of the C syntax "test_a == &test_a", and the & operator is ignored, and thus you are passing the address of the function as the pointer to the data.
You will need to store the function pointer on the stack/heap before passing it to the ffi_call. E.g.
..
void* arg_values[1];
arg_values[0] = (void*)test_a;
values[0] = &(arg_values[0]);
...
Regards,
Nathan