Accessing an ObjC object from a C function callbac

2019-07-04 06:24发布

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?

[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.

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!

3条回答
小情绪 Triste *
2楼-- · 2019-07-04 06:46

You're reinventing the wheel. Use a wrapper:

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楼-- · 2019-07-04 06:51

Example code

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

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent,
                         void *userData)
{
    [(yourAppDelegate *)userData dosomething];
}
查看更多
淡お忘
4楼-- · 2019-07-04 07:00

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.

查看更多
登录 后发表回答