framework swift C C++ 混編

最近在寫一個 swiftframework 時遇到一個問題。
在此做個記錄,方便自己也方便他人。
問題描述:
swift framework 中有用到一個 C++ 的算法,
因為 swift 不能直接調用 C++,只能通過 C 或者 OC 橋接調用。
在 純 swift 項目中,在橋接文件中直接包含 C 或者 OC 頭文件,即可混編。 可是在 framework 中不可以使用橋接頭文件,只能使用 modulemap 代替橋接頭文件。

具體步驟:

1.導入 C++ 文件到 framework

2.編寫 swiftC++ 的橋接 C 函數(shù)

因為 swift 不能直接調用 C++,只能通過 C 或者 OC 橋接調用。在此我們選用 C 作為橋接。

image.png

#ifndef SPLineExt_h
#define SPLineExt_h

#ifdef __cplusplus
extern "C" {
#endif

double c_splineValue(const double *x,int x_len,
                   const double *y,int y_len,
                   double p_x);

#ifdef __cplusplus
}
#endif

#endif /* SPLineExt_h */

因為要用到的 C++ 代碼在 SPLine.cpp 類文件中,所以上面寫的 C 函數(shù)實現(xiàn)寫在 SPLine.cpp 中。

double c_splineValue(const double *x,int x_len,
                   const double *y,int y_len,
                   double p_x){
    std::vector<double> v_x;
    for (int i = 0; i<x_len; i++) {
        v_x.push_back(x[i]);
    }

    std::vector<double> v_y;
    for (int i = 0; i<y_len; i++) {
        v_y.push_back(y[i]);
    }

    SPLine sp = SPLine(v_x, v_y);
    double d = sp(p_x);

    return d;
}

3.新建 module.modulemap 文件

更多 modulemap 語法

framework module VCBle {
   umbrella header "../VCBle.h"
   export *
   module * { export * }
   
   explicit module Spline_Private {
      header "../SPLineCPP/SPLineExt.h"
      export *
   }
}

4.設置 Xcode 中 modulemap path

Targets/Build Setting/ Module Map File

image.png

Targets/Build Setting/ Import paths

image.png

5. 測試調用 C++ 函數(shù)

在需要用到 C++ 函數(shù)的 swift 代碼中測試下

import VCBle.Spline_Private

public func swift_getSplineValue() -> Double {
    let x:[Double] = [0.1, 0.4, 1.2, 1.8, 2.0]
    let y:[Double] = [0.1, 0.7, 0.6, 1.1, 0.9]
    let d = c_splineValue(x, Int32(x.count), y, Int32(y.count), 1.5)
    return d
}

測試打印結果:
spline value:%.f 0.9153451492537314

swift 完美調用了 c++ 代碼!

參考文章

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容