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

后端 未结 2 1942
南笙
南笙 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 <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;
    }
    
    0 讨论(0)
  • 2021-02-04 04:48

    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.

    0 讨论(0)
提交回复
热议问题