目标C中的函数指针 [英] Function Pointers in Objective C
问题描述
快速的问题。有谁知道如何获得一个客观的C方法的函数指针?
我可以声明一个C ++方法作为函数指针,但这是一个回调方法,因此C ++方法需要成为类的一部分,以便它可以访问实例字段。我不知道如何使C ++方法成为目标C类的一部分。任何建议?
Quick question. Does anyone know how to get the function pointer of an objective c method? I can declare a C++ method as a function pointer, but this is a callback method so that C++ method would need to be part of the class SO THAT IT CAN ACCESS THE INSTANCE FIELDS. I don't know how to make a C++ method part of an objective c class. Any suggestions?
推荐答案
通常,您需要两条信息才能回调Objective-C;要调用的方法以及调用它的对象。无论是选择器还是只是IMP - instanceMethodForSelector:
结果 - 都是足够的信息。
Typically, you need two pieces of information to call back into Objective-C; the method to be invoked and the object to invoke it upon. Neither just a selector or just the IMP -- the instanceMethodForSelector:
result -- will be enough information.
大多数回调API提供的上下文指针被视为传递给回调的不透明值。这是你难题的关键。
Most callback APIs provide a context pointer that is treated as an opaque value that is passed through to the callback. This is the key to your conundrum.
I。如果你有一个回调函数声明为:
I.e. if you have a callback function that is declared as:
typedef void (*CallBackFuncType)(int something, char *else, void *context);
以及一些API消耗指针的回调函数类型:
And some API that consumes a pointer of said callback function type:
void APIThatWillCallBack(int f1, int f2, CallBackFuncType callback, void *context);
然后你就可以实现你的回调了:
Then you would implement your callback something like this:
void MyCallbackDude(int a, char *b, void *context) {
[((MyCallbackObjectClass*)context) myMethodThatTakesSomething: a else: b];
}
然后你会调用API类似于这个:
And then you would call the API something akin to this:
MyCallbackObjectClass *callbackContext = [MyCallbackObjectClass new];
APIThatWillCallBack(17, 42, MyCallbackDude, (void*)callbackContext);
如果您需要在不同的选择器之间切换,我会建议创建一个位于回调和Objective-C API。根据传入的回调数据,glue类的实例可以包含必要的配置或必要的选择逻辑。
If you need to switch between different selectors, I would recommend creating a little glue class that sits between the callback and the Objective-C API. The instance of the glue class could contain the configuration necessary or logic necessary to switch between selectors based on the incoming callback data.
这篇关于目标C中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!