函数指针指向objc类成员方法,用于C ++?

时间:2017-04-09 00:07:52

标签: c++ ios objective-c function-pointers

我有一个用于网络的C ++类(通过boost :: asio),它需要使用回调函数才能做任何有用的事情。 我还有一个混合的Objective-C ++项目,它使用了这个类。 使用objc类单例,我的每个子类UIViewController类都能够绑定到类实现文件中定义的标准C / C ++方法,而这些方法又通过单例实例调用它们各自的类成员方法: / p>

@interface MyViewControllerClass ()
+ (instancetype)Instance;
@end

MyViewControllerClass *_MyViewControllerClass_Instance;

void cppCallback() {
    // This method gets called from the C++ class
    [[MyViewControllerClass Instance] objcCallback];
}

@implementation MyViewControllerClass

+ (instancetype)Instance {
    return _MyViewControllerClass_Instance;
}

- (void)viewDidLoad
{
    _MyViewControllerClass_Instance = self;
    // Pass &cppCallback to the C++ class here, so it can be called later
}

- (void)objcCallback {
    ;// Do something here
}
@end

看起来很丑陋,过去这种方法运作得很好。但是现在我已经开了一堵新墙...... 我需要在UICollectionViewCell子类中使用C ++网络类,这将有许多实例...这意味着使用单例将无法工作。

那么如何将指向objc类方法的指针作为C ++参数传递?
我唯一的选择是为我的C ++网络类编写一个完整的Objective-C包装器类吗?

1 个答案:

答案 0 :(得分:1)

"功能指针"这里不可能,因为你不能使用函数指针调用实例方法(除非你用函数指针传递实例)。

但是,您可以创建一个可调用对象。

struct Callback {
    MyViewControllerClass *instance;
    void operator()() {
        [instance objcCallback];
    }
};

你也可以使用C ++ lambda,它有点模糊。