Wrapping C Library with Objective-C - Function Pointers

I am writing a wrapper around the C library in Objective-C. The library allows me to register callback functions when certain events occur.

The register_callback_handler () function takes a function pointer as one of the parameters.

My question to you, the programming guru, is this: how can I present the call / selector of the Objective-C method as a function pointer?

  • Will NSInvocation be useful in this situation or too high?
  • Would it be better if I just wrote a C function in which there is a method call written inside it, and then pass a pointer to this function?

Any help would be great, thanks.

+3
source share
1 answer

Does register_callback_handler()the context argument use (void *)? Most callback APIs do.

If so, then you can easily use NSInvocation. Or you can select a small structure that contains a reference to an object and a selector, and then select its own call.

If it takes only a function pointer, then you will potentially be pushing. You need something somewhere that uniquely identifies the context, even for pure C coding.

Given that your callback handler has a context pointer, you are all set up:

typedef struct {
    id target;
    SEL selector;
    // you could put more stuff here if you wanted
    id someContextualSensitiveThing;
} TrampolineData;

void trampoline(void *freedata) {
    TrampolineData *trampData = freedata;
    [trampData->target performSelector: trampData->selector withObject: trampData-> someContextualSensitiveThing];
}

...
TrampolineData *td = malloc(sizeof(TrampolineData));
... fill in the struct here ...
register_callback_handler(..., trampoline, td);

. / , , . - objc_msgSend() , ( , objc_msgSend_stret()).

+3

Source: https://habr.com/ru/post/1716399/


All Articles