从C函数回调访问ObjC对象。

时间:2021-05-24 15:53:13

I'm playing around a bit with global hot keys in Carbon, and I registered a hot key. When the hot key is pressed, this function is called:

我在用碳的全局热键,注册了一个热键。当按下热键时,这个函数被称为:

OSStatus myHotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData) {
    ...
}

This function is in the same file as my app delegate's definition. How do I now call an ObjC method on my delegate in that function?

这个函数与我的app委托定义在同一个文件中。如何调用委托中的ObjC方法?

[self aMethod];

I cant add a void* (to be a pointer to my class instance) to the C function, because I am not the one calling it.

我不能将void*(作为类实例的指针)添加到C函数中,因为调用它的不是我。

I tried to convert the method into a class method and then call it with [AppDelegate aFunction], which works but then I cant use my instance variables!

我试着把这个方法转换成类方法,然后用[AppDelegate aFunction]调用它,它可以工作,但是我不能使用实例变量!

3 个解决方案

#1


5  

Give the pointer to your class instance as parameter for userData when you register your event handler. You will then get this pointer back inside the handler as userData.

在注册事件处理程序时,将指向类实例的指针作为userData的参数。然后将该指针作为userData返回到处理程序中。

#2


8  

You're reinventing the wheel. Use a wrapper:

你重新发明*。使用一个包装器:

http://github.com/davedelong/DDHotKey

http://github.com/davedelong/DDHotKey

well perhaps not a wheel, since hot keys aren't "trivial" concepts. maybe you're reinventing a differential? or something? ;)

也许不是*,因为热键不是“琐碎”的概念。也许你在重新发明一个微分方程?还是什么?,)

#3


3  

Example code

示例代码

InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,(void *)self,NULL);
...

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent,
                         void *userData)
{
    [(yourAppDelegate *)userData dosomething];
}

#1


5  

Give the pointer to your class instance as parameter for userData when you register your event handler. You will then get this pointer back inside the handler as userData.

在注册事件处理程序时,将指向类实例的指针作为userData的参数。然后将该指针作为userData返回到处理程序中。

#2


8  

You're reinventing the wheel. Use a wrapper:

你重新发明*。使用一个包装器:

http://github.com/davedelong/DDHotKey

http://github.com/davedelong/DDHotKey

well perhaps not a wheel, since hot keys aren't "trivial" concepts. maybe you're reinventing a differential? or something? ;)

也许不是*,因为热键不是“琐碎”的概念。也许你在重新发明一个微分方程?还是什么?,)

#3


3  

Example code

示例代码

InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,(void *)self,NULL);
...

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent,
                         void *userData)
{
    [(yourAppDelegate *)userData dosomething];
}