Say I have a function that expects a block:
void foo(Foo (^block)(Bar));
And say I have a function with the same signature, except not a block:
Foo myFunction(Bar);
I can do this:
foo(^(Bar bar) { return myFunction(bar); });
But I would rather do this, which would be equivalent if it worked:
foo(&myFunction);
If I try to, XCode says:
No matching function for call to 'foo'
A block is a function pointer together with some context, so on that level it seems reasonable to want to use a plain function pointer as a block with an empty context. Is it possible?
The problem, though, is that a block is not a function pointer together with some context.
A block captures executable code during compilation and state during execution. The executable code follows the C ABI in terms of passing arguments but, like method calls, it has some very specific requirements. Translating it to a C function declaration, a block that returns a
BOOLand takes a singleintargument would look like this:That is, the first argument to the block’s “function” must be a pointer to the block itself.
Thus, no, you can’t just rip out the block’s “function” pointer and cast it to/from a C function.