将实例方法作为函数指针传递给C库

时间:2013-03-01 12:25:47

标签: objective-c c function-pointers

我正在编写一个使用C库的Objective-C应用程序。我目前面临的问题是C库有一个结构,其中某些字段是稍后用作回调的函数指针。如何将Objective-C实例方法转换为函数指针并将其传递给库?

1 个答案:

答案 0 :(得分:19)

您需要在Objective-C类实现文件中提供C回调函数,这仅在回调能够使用某种 context 指针时才有效。

所以想象一下C回调签名是这样的:

void myCallback(void *context, int someOtherInfo);

然后在Objective-C类实现文件中,您需要使用该回调将trampoline返回到Objective-C类(使用 context 指针作为要调用的类的实例):< / p>

// 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];
}

如果你的C回调函数不接受某种上下文信息,那么:

  1. 它已经坏了,应该修复/报告为错误。
  2. 您需要依赖于在全局,静态范围内存储指针到自身以供C回调函数使用。这会将MyClass的实例数限制为一个!
相关问题