我正在编写一个使用C库的Objective-C应用程序。我目前面临的问题是,该C库具有一个结构,其中某些字段是函数指针,稍后用作回调。如何将Objective-C实例方法转换为函数指针并将其传递给库?
我正在编写一个使用C库的Objective-C应用程序。我目前面临的问题是,该C库具有一个结构,其中某些字段是函数指针,稍后用作回调。如何将Objective-C实例方法转换为函数指针并将其传递给库?
void myCallback(void *context, int someOtherInfo);
然后,在 Objective-C 类的实现文件中,您需要使用该回调函数来跳回到您的 Objective-C 类(使用 context 指针作为要调用的类的实例):
// 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];
}
MyClass
实例的数量为一个!
(__bridge MyClass *)
吗? - trojanfoe