例如通过方法函数指针C库 [英] Pass instance method as function pointer to C Library

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

问题描述

我写一个使用C库Objective-C的应用程序。我目前面临的问题是,C库,其中有一些场均函数指针后用作回调的结构。我怎么能一个Objective-C的实例方法转换为一个函数指针,并把它传递给库?

I am writing an Objective-C application that uses a C Library. The issue which i am currently facing is that the C Library has a structure where some field are function pointers later used as callbacks. How can i convert an Objective-C instance method to a function pointer and pass it to the library?

推荐答案

您需要提供的Objective-C类实现文件中以C回调函数,这只会工作,如果回调能够使用的上下文的某种指针。

You will need to provide the C callback function within the Objective-C class implementation file, and this will only work if the callback is able to use a context pointer of some sort.

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

So imagine the C callback signature is like this:

void myCallback(void *context, int someOtherInfo);

然后,Objective-C类实现文件中,你需要使用回调蹦床回到您的Objective-C类(使用的背景的指针作为类的实例来调用):

Then within the Objective-C class implementation file you need to use that callback to trampoline back into your Objective-C class (using the context pointer as the instance of the class to invoke):

// 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回调函数不接受某种的背景的信息,则:

If your C callback function does not accept some sort of context info, then:


  1. 这是坏了,这应该是固定/报告的错误。

  2. 您将需要依靠存储的指针到自我的在全球,静态的,范围可以通过C回调函数使用。这将 MyClass的的实例的数量限制到一个!

  1. It's broken and this should be fixed/reported as a bug.
  2. You will need to rely on storing a pointer-to-self at global, static, scope to be used by the C callback function. This will limit the number of instances of MyClass to one!

这篇关于例如通过方法函数指针C库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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