I am writing an Objective-C class but it uses an API written in C. This is mostly fine as mixing C calls with Objective-C calls causes few problems.
However one of the API call requires a call back method (example):
success = CFHostSetClient(host, MyCFHostClientCallBack, &context);
Where MyCFHostClientCallBack is a C function defined like this:
static void MyCFHostClientCallBack(CFHostRef host, CFHostInfoType typeInfo, const CFStreamError *error, void *info);
- Can/How do I call an Objective-C method in place of this?
- Can/Should I mix C functions with my Objective-C calls?
- How do I mix C functions with Objective-C methods?
Mixing C and Objective-C methods and function is possible, here is a simple example that uses the SQLite API within an iPhone App: (course site)
C functions need to be declared outside of the
@implementationin an Objective-C (.m) file.Because the C function is outside of the
@implementationit cannot call methods likeand has no access to ivars.
This can be worked around as long as the call-back function takes a
userInfoorcontexttype parameter, normally of typevoid*. This can be used to send any Objective-C object to the C function.As in the sample code, this can be manipulated with normal Objective-C operations.
In addition please read this answer: Mixing C functions in an Objective-C class