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

后端 未结 2 1944
南笙
南笙 2021-02-04 04:15

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 mai

2条回答
  •  一个人的身影
    2021-02-04 04:23

    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 
    
    // 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;
    }
    

提交回复
热议问题