I have to provide a C-style callback for a specific C library in an iOS app. The callback has no void *userData
or something similar. So I am not able to loop in a context. I'd like to avoid introducing a global context to solve this. An ideal solution would be an Objective-C block.
My question: Is there a way to 'cast' a block into a function pointer or to wrap/cloak it somehow?
Objective-C programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type. Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function −.
A block declaration follows the next syntax pattern: This is quite similar to a C function declaration, with one great exception: The caret (^) symbol, which indicates that the declared object is a block. Let’s see everything one by one: ReturnType: Any data type Objective-C supports, or void if the block returns nothing.
Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −. type *var-name; Here, type is the pointer's base type; it must be a valid Objective-C data type and var-name is the name of the pointer variable.
Objective-C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. Objective-C allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
MABlockClosure can do exactly this. But it may be overkill for whatever you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With