framework swift C C++ 混编

最近在写一个 swiftframework 时遇到一个问题。
在此做个记录,方便自己也方便他人。
问题描述:
swift framework 中有用到一个 C++ 的算法,
因为 swift 不能直接调用 C++,只能通过 C 或者 OC 桥接调用。
在 纯 swift 项目中,在桥接文件中直接包含 C 或者 OC 头文件,即可混编。 可是在 framework 中不可以使用桥接头文件,只能使用 modulemap 代替桥接头文件。

具体步骤:

1.导入 C++ 文件到 framework

2.编写 swiftC++ 的桥接 C 函数

因为 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 函数实现写在 SPLine.cpp 中。

double c_splineValue(const double *x,int x_len,
                   const double *y,int y_len,
                   double p_x){
    std::vector v_x;
    for (int i = 0; i v_y;
    for (int i = 0; i

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++ 函数

在需要用到 C++ 函数的 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++ 代码!

参考文章

你可能感兴趣的:(framework swift C C++ 混编)