4

Is it possible create an IMP where the number of parameters matches the selector for the instance method being resolved?

I could use an 'if' statement and a finite number of parameters (say between 0 and 10), but is it possible to have eg IMP_implementationWithBlock with va_args ?

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • 1
    It sounds from your recent posts like you might be getting into territory where you want to look at libffi, if you haven't already. I've got a two projects on GitHub that use libffi for stuff like this: [WoolBlockInvocation](https://github.com/woolsweater/WoolBlockInvocation) and [WoolDelegate](https://github.com/woolsweater/WoolDelegate). SO posts about them: [In ObjC, can you write a function that combines 2 blocks?](http://stackoverflow.com/a/17892240), [Creating delegates on the spot with blocks](http://stackoverflow.com/a/16113046). You might find them interesting. – jscs Aug 18 '13 at 04:44
  • Thanks Josh. . I played with libextobjc aspects (based on libffi) but ran into some crashes (this libs' AOP implementation is still experimental). . . So I know roughly what libffi can do, but that's as far as my experience goes so far. I'll check out those libraries and posts. . . any other references/places to learn would be helpful too. – Jasper Blues Aug 18 '13 at 04:53
  • It can be touchy to pass objects in and out of `void *`, especially if you want to use ARC. Mike Ash has good info, as I've mentioned below. I'm pretty sure there are a few more resources; let me try to dig them up. – jscs Aug 18 '13 at 05:04

1 Answers1

2

You can't create a function at runtime in C; the number of parameters has to be known at compile time.

You can use a variadic function to pretend that you have a function with any number of arguments, (I've included this usage in a recent project) but this may not be portable and is probably Undefined Behavior.

If you need to move arguments between functions where the signatures and arguments are not known until runtime, you almost certainly want to look into libffi.

Mike Ash has a few really useful posts about it: http://www.mikeash.com/pyblog/?tag=libffi that's where I got started and learned most of what I know about it.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Update: Using a variadic function is no longer recommended, as with arm64 the args go direct to registers. We now use the 'forwardInvocation' method. – Jasper Blues May 24 '14 at 01:25