Eike Cochu
Eike Cochu

Reputation: 3429

Accessing an ObjC object from a C function callback

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!

Upvotes: 3

Views: 479

Answers (3)

Chanok
Chanok

Reputation: 800

Example code

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

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

Upvotes: 3

Dave DeLong
Dave DeLong

Reputation: 243146

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? ;)

Upvotes: 8

x4u
x4u

Reputation: 14077

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.

Upvotes: 5

Related Questions