最近在寫一個
swift的framework時遇到一個問題。
在此做個記錄,方便自己也方便他人。
問題描述:
swift framework 中有用到一個C++的算法,
因為swift不能直接調用C++,只能通過C或者OC橋接調用。
在 純 swift 項目中,在橋接文件中直接包含C或者OC頭文件,即可混編。 可是在 framework 中不可以使用橋接頭文件,只能使用modulemap代替橋接頭文件。
具體步驟:
1.導入 C++ 文件到 framework 中
2.編寫 swift 與 C++ 的橋接 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 文件
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++ 代碼!