Alex Rivera | Logout

Pass a block to a C++ method from objective C

Asked 2011-05-16T07:18:37.570
19

I have a C++ helper class that I use with objective-C. I would like to pass the c++ class a block from a view controller (a callback) so that when it is executed I am on the main thread and can update the UI. I currently have a similar system working with function pointers and performSelector when the function is called. I would like an example of how to set up the c++ variable and how to pass an objective-C block to it and call it from the c++ class.

If this is not possible, can you think of another/better solution?

Edit
Report

1 Answer

10

See Using a Block as a Function Argument. When declaring your method, use a syntax similar to the following to declare a block argument:

void theFunction(blockReturnType (^argumentName)(blockArgumentTypes));

A block call looks like a function call, so an implementation of theFunction above which simply calls the block and returns its result would look like this:

int theFunction(int anArgument, int (^theBlock)(int)) {
    return theBlock(anArgument);
}

This syntax will work for C, C++, and Objective-C.

answered 2011-05-19T23:00:02.457

Your Answer