我正在编写一个使用C库的Objective-C应用程序。我目前面临的问题是,C库有一种结构,其中一些字段是函数指针,后来用作回调。如何将Objective-C实例方法转换为函数指针并将其传递给库?
发布于 2013-03-01 20:34:42
您将需要在Objective-C类实现文件中提供C回调函数,并且只有当回调能够使用某种上下文指针时,这才能起作用。
所以想象一下C回调签名是这样的:
void myCallback(void *context, int someOtherInfo);
然后在Objective-C类实现文件中,您需要使用该回调来弹回您的Objective-C类(使用上下文指针作为要调用的类的实例):
// 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回调函数不接受某种上下文信息,那么:
MyClass
的实例数限制为一个!https://stackoverflow.com/questions/15157759
复制相似问题