结束语C库用Objective-C的 - 函数指针 [英] Wrapping a C Library with Objective-C - Function Pointers

查看:145
本文介绍了结束语C库用Objective-C的 - 函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写周围的Objective-C的C库的包装。该库可以让我发生特定事件时注册回调函数。

I'm writing a wrapper around a C library in Objective-C. The library allows me to register callback functions when certain events occur.

该register_callback_handler()函数的函数指针作为参数之一。

The register_callback_handler() function takes a function pointer as one of the parameters.

我给你的大师编程的​​问题是:我怎样才能重新present一个Objective-C的方法调用/选择器作为函数指针

My question to you gurus of programming is this: How can I represent an Objective-C method call / selector as a function pointer?


  • 应该NSInvocation的是有用的在这种情况下什么过高的水平?

  • 我会过得更好只是写有里面写的方法调用C函数,然后将指针传递给该函数?

任何帮助将是巨大的,谢谢。

Any help would be great, thanks.

推荐答案

确实 register_callback_handler()也采取了(无效*)上下文参数?多数回调的API做的。

Does register_callback_handler() also take a (void*) context argument? Most callback APIs do.

如果确实如此,那么你可以使用NSInvocation的很容易。或者你可以分配包含对象和选择的引用,然后凑齐了自己的呼叫一点结构。

If it does, then you could use NSInvocation quite easily. Or you could allocate a little struct that contains a reference to the object and selector and then cobble up your own call.

如果只需要一个函数指针,那么你就可能大清洗。你需要的东西的地方,唯一标识的背景下,即使是纯C编码。

If it only takes a function pointer, then you are potentially hosed. You need something somewhere that uniquely identifies the context, even for pure C coding.

由于您的回调处理程序的确实的有上下文指针,你都设置:

Given that your callback handler does have a context pointer, you are all set:

typedef struct {
    id target;
    SEL selector;
    // you could put more stuff here if you wanted
    id someContextualSensitiveThing;
} TrampolineData;

void trampoline(void *freedata) {
    TrampolineData *trampData = freedata;
    [trampData->target performSelector: trampData->selector withObject: trampData-> someContextualSensitiveThing];
}

...
TrampolineData *td = malloc(sizeof(TrampolineData));
... fill in the struct here ...
register_callback_handler(..., trampoline, td);

这是一般的想法,反正。如果您需要处理非对象类型参数和/或回调,就有点有点棘手,但不算多。最简单的办法就是让编译器生成正确的判罚网站(请记住,你可能需要使用objc_msgSend_stret()为结构的返回类型),其类型转换为正确的类型的函数指针后直接调用objc_msgSend()。

That is the general idea, anyway. If you need to deal with non-object typed arguments and/or callbacks, it gets a little bit trickier, but not that much. The easiest way is to call objc_msgSend() directly after typecasting it to a function pointer of the right type so the compiler generates the right call site (keeping in mind that you might need to use objc_msgSend_stret() for structure return types).

这篇关于结束语C库用Objective-C的 - 函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆