I have a function:
myFunction (MyProc callback, void * ref)
This function is called from within an Objective-C class. The function is passed a pointer to the callback (a function in the class) and a reference. The reference is necessary because the callback is called statically and therefore doesn’t have a context. The ref can be used to provide a context to the callback.
I want to be able to pass the Objective-C class as the reference. So the question is:
How do I cast an NSObject to a void * and how do I cast a void * as an NSObject.
Thanks in advance.
Do something like this:
Note that
CFBridgingRetain()andCFBridgingRelease()are macros around compiler attributes. Feel free to use either. I like the API variant as it is in more common use in our codebases and it is more explicitly / less confusing.CFBridgingRetain()effectively hard-retains the object that must be balanced by aCFBridgingRelease(). It also happens to return aCFTypeRefwhich is compatible with a cast tovoid*.CFBridgingRelease()effectively undoes that hard-retain and, thus,qwill only remain valid within the scope thatois valid.Valid for basic callbacks, but you’d probably not what that with a
void *context;type thing that has to stick around for a while. For that:Note that Xcode is quite good about suggesting exactly what you should do if you leave out the cast / API call. It even explains the meanings of each of the alternative solutions (I relied on this heavily until I could keep ’em straight in my head).