in reply to [OT: C] Getting pointers to functions

because I want to provide a perl wrapping for an mpfr function that takes a "pointer to function" as one of its arguments

Usually, the reason for passing a function pointer to another function is so the called function can either call the other function, or set up a call-back so something else (like an event handler) can call it.

That means you need to provide an address that is "local" to the function you are passing the pointer to.

With static linking, your XSubs will be in the same address space as the functions you want pointers to.

With dynamic linking, the addresses your Xsub will have will be "mapped" addresses. That is, addresses in the XSub's address space that it can use to call the functions in the DLL's address space.

I would suggest creating a C array of function pointers initialized to the addresses of the functions you need pointers for:

funcp FuncArray[] = { mpfr_mul, mpfr_read, /* etc */ }

Then your XSub can fetch the needed pointer by index.

To avoid having to figure out the indexes, you can use Perl to read the C source of FuncArray and create a hash with the function names as keys and indexes as values.

Replies are listed 'Best First'.
Re^2: [OT: C] Getting pointers to functions
by syphilis (Archbishop) on Jan 05, 2017 at 08:18 UTC
    I would suggest creating a C array of function pointers initialized to the addresses of the functions ...

    Yes, I think that would have been a good starting point if I had stayed with my original intention.
    However, in a subsequent discussion on the mpfr mailing list it was suggested that the best approach would be to rewrite mpfr_round_nearest_away() in perl, rather than wrapping it.
    (This avoids the C99 requirement, avoids having to accommodate different C function prototypes and further allows the user to obtain "round to nearest, ties away from zero" for functions that the user might create.)

    So I'm going with that approach. It's only a few lines of code and instead of using pointers to the mpfr library functions, it uses code references to the XS subs that wrap those mpfr library functions.

    Calling it will be as simple as rndna(\&Rmpfr_foo, $rop, @args) where @args are the input args appropriate for the function Rmpfr_foo.

    So there was a strong element of "XY problem" after all - largely due to the damned blinkers I habitually like to wear.

    Cheers,
    Rob