将Objective-C方法传递给C++方法

Passing Objective-C method to c++ method

本文关键字:方法 C++ Objective-C      更新时间:2023-10-16

我在Objective-C中创建了void类型方法,将其传递给如下所示的C++方法:

Objective-C方法将传递到的C++方法:

glfwSetWindowSizeCallback(m_Window, windowResize);

这里是Objective-C方法:

- (void) windowResize:(GLFWwindow *)window :(int)width :(int)height {glViewport(0, 0, width, height);}

我知道可以通过向项目中添加C++文件并用C++方法将其链接到.m文件来解决这个问题,但我想用Cocoa语法

实现它

ObjC方法可以像一样作为选择器传递

SEL method = @selector(windowResize:width:height:);
glfwSetWindowSizeCallback(m_Window, method);

然后在glfwSetWindowSizeCallback内部应用。或者,您可以将ObjC调用封装在c函数中并传递函数指针。

一个更完整的例子可能是:

void func(NSApplication * target, SEL method) {
    if ([target respondsToSelector: method] ) {
       [target performSelector:method];
    }
}

其他地方:

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    SEL method = @selector(unhideAllApplications:);
    func([NSApplication sharedApplication] , method);
  }