我正在编写一个使用 C 库的 Objective-C 应用程序。我目前面临的问题是 C 库有一个结构,其中一些字段是函数指针,后来用作回调。如何将 Objective-C 实例方法转换为函数指针并将其传递给库?
最佳答案
您需要在 Objective-C 类实现文件中提供 C 回调函数,这仅在回调能够使用某种上下文指针时才有效。
所以想象一下 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];
}
如果您的 C 回调函数不接受某种上下文信息,则:
- 它坏了,这应该被修复/报告为一个错误。
- 您需要依赖于在全局静态范围内存储一个指向自身的指针,以供 C 回调函数使用。这会将
MyClass
的实例数限制为一个!
关于objective-c - 将实例方法作为函数指针传递给 C 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157759/