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

2019-03-12 12:25发布

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?

2条回答
Melony?
2楼-- · 2019-03-12 12:41

So is it just that you're not entirely familiar with the block syntax? If so, here's a quick example that should hopefully make sense if you're already familiar with function pointers (the syntax is more or less the same, but with the use of an ^ for declaring one [creating a closure is, of course, different]).

You probably want to set up a typedef for the block types just to save yourself repeating the same thing over and over, but I included examples for both using a typedef and just putting the block type itself in the parameters.

#import <Cocoa/Cocoa.h>

// do a typedef for the block
typedef void (^ABlock)(int x, int y);

class Receiver
{
public:
    // block in parameters using typedef
    void doSomething(ABlock block) {
        block(5, 10);
    }

    // block in parameters not using typedef
    void doSomethingToo(void (^block)(int x, int y)) {
        block(5, 10);
    }
};


int main (int argc, char const *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Receiver rcv;
    // pass a block
    rcv.doSomething(^(int x, int y) { NSLog(@"%d %d", x, y); });
    rcv.doSomethingToo(^(int x, int y) { NSLog(@"%d %d", x, y); });

    [pool drain];
    return 0;
}
查看更多
Root(大扎)
3楼-- · 2019-03-12 12:52

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.

查看更多
登录 后发表回答