Pass instance method as function pointer to C Library

会有一股神秘感。 提交于 2019-12-02 20:34:28

You will need to provide the C callback function within the Objective-C class implementation file, and this will only work if the callback is able to use a context pointer of some sort.

So imagine the C callback signature is like this:

void myCallback(void *context, int someOtherInfo);

Then within the Objective-C class implementation file you need to use that callback to trampoline back into your Objective-C class (using the context pointer as the instance of the class to invoke):

// Forward declaration of C callback function
static void theCallbackFunction(void *context, int someOtherInfo);

// Private Methods
@interface MyClass ()
- (void)_callbackWithInfo:(int)someOtherInfo;
@end

@implementation MyClass

- (void)methodToSetupCallback
{
    // Call function to set the callback function, passing it a "context"
    setCallbackFunction(theCallbackFunction, self);
    ...
}

- (void)_callbackWithInfo:(int)someOtherInfo
{
    NSLog(@"Some info: %d", someOtherInfo);
}

@end

static void theCallbackFunction(void *context, int someOtherInfo)
{
    MyClass *object = (MyClass *)context;
    [object _callbackWithInfo:someOtherInfo];
}

If your C callback function does not accept some sort of context info, then:

  1. It's broken and this should be fixed/reported as a bug.
  2. You will need to rely on storing a pointer-to-self at global, static, scope to be used by the C callback function. This will limit the number of instances of MyClass to one!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!