GEEK ALERT! If you don't

GEEK ALERT! If you don’t want to read a technical programming discussion, skip this entry

Problem: I need to call any arbitrary function from a shared library, not knowing in advance how many arguments it requires. This is to be done in PowerPC code running under MacOS X.

I spent the last few days up to my neck in PowerPC assembly code (which I understand only enough to get myself into trouble). I finally came up with something like this, which doesn’t use any assembler:

long callfunc(FunctionPtr func,long *ap)


return (*func)(ap[0], ap[1], ap[2], ap[3], ap[4], ap[5], ap[6], ap[7],

ap[8], ap[9], ap[10], ap[11], ap[12], ap[13], ap[14], ap[15], ap[16], ap[17]);


This takes advantage of the fact that the caller, not the function being called cleans up the stack, and since the first 8 arguments are passed in registers and the remaining ones are passed at fixed offsets, the function being called can ignore any arguments it doesn’t use.

I’ve made the assumption that there’ll never be more than 18 arguments – I’ve never seen a toolbox function that takes more than 10. I’m also not handling floating point arguments, which need to be passed in FPRs instead of GPRs, but once again, I won’t be dealing with any toolbox functions that use floating point.

The application will be extensible by adding new shared libraries, so we’ll have to stay within these restrictions for our own code.

Comments are closed.