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: Function pointers?


I think it works now with the recommended changes. I was just under
the impression that values[0] and the value of ptr in test_b should
agree.  Since I am actually able to call the function with the ptr
passed, I take it that that was a false assumption?

On Tue, Mar 5, 2013 at 6:44 AM, The Devils Jester
<thedevilsjester@gmail.com> wrote:
> I am not sure how that makes a difference.  With the above change, the
> value stored in values[0] and the actual ptr printed in test_b are
> still different.  Am I missing something obvious here?
>
> On Tue, Mar 5, 2013 at 1:46 AM, Nathan Rossi <nathan.rossi@xilinx.com> wrote:
>>> -----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
>>
>>


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