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

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

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

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

void myCallback(void *context, int someOtherInfo); 

然后在Objective-C类实现文件中,您需要使用该回调将trampoline重新放回到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回调函数不接受某种上下文信息,那么:

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