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

后端 未结 2 1970
南笙
南笙 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: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.

提交回复
热议问题