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?
When do we pass arguments by reference or pointer? 1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function. For example, consider the following example program where fun () is able to modify local variable x of main ().
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Pointer to functions. It is possible to declare a pointer pointing to a function which can then be used as an argument in another function. A pointer to a function is declared as follows, type (*pointer-name)(parameter); Here is an example : int (*sum)(); int *sum(); A function pointer can point to a specific function when it is assigned ...
Passing pointer to a function. If a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function. This is because only a copy of the pointer is passed to the function. It can be said that “pass by pointer” is passing a pointer by value.
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 BOOL
and takes a single int
argument would look like this:
BOOL blockLikeFunc(void *block, int arg) { ... }
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.
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