如何实现从C ++函数到Swift的回调

时间:2018-08-28 18:45:00

标签: c++ ios swift callback

我尝试在cpp类中执行某些操作,并且在执行该函数时将回调返回swift。

所以我做这些事情:

  1. callbackClass.cpp

    中创建此功能
    int callback::run(void (*callback)(int))
     {
         for (unsigned int i = 0; i < 100; i++)
         {
             callback(i);
         }
         return 0;
     }
    
  2. callbackClass.hpp中:

    class callbackClass.hpp
    {
      .
      .
      .
      public:
         int run(void (*callback)(int));
    };
    
    #endif
    
  3. 对于header.h‍‍

    int callback(void (*callback)(int));
    

Swift端记录回调之前,这是很好的:

func callbackFunc(){

  callback({valueFromCallback in //call cpp function

    print(valueFromCallback) //Works fine

  })
}

但是当尝试做其他事情时:

func callbackFunc(){

  var value : String!

  callback({valueFromCallback in //call cpp function

    value = String(valueFromCallback) //It has a problem

  })
}

Xcode返回此错误:

  

不能从捕获上下文的闭包中形成C函数指针

我已经看过这些问题,但没有帮助:

Swift: Pass data to a closure that captures context

How to cast self to UnsafeMutablePointer<Void> type in swift

A C function pointer cannot be formed from a closure that captures context

1 个答案:

答案 0 :(得分:0)

最终我意识到可以将'closure'作为参数传递给c ++

因此,首先我在Swift类中创建一个Closure:

typealias closureCallback = (Int32) -> ()

然后将其传递给cpp端:

  1. header.h‍‍

    int callback(void (^closureCallback)(int));
    
  2. callbackClass.hpp中:

    class callbackClass.hpp
    {
      .
      .
      .
    
      public:
          int run(void (^closureCallback)(int));
    };
    
    #endif
    
  3. callbackClass.cpp

    int callback::run(void (^closureCallback)(int))
     {
         for (unsigned int i = 0; i < 100; i++)
         {
             closureCallback(i);
         }
         return 0;
     }
    

最后在Swift中处理它:

typealias closureCallback = (Int32) -> ()

func callbackFunc(){

  var value : String!

  let closureValue: closureCallback = {valueFromclosureCallback in
      value = String(valueFromclosureCallback)
   }

    callback(closureValue) //call cpp function

}