Swift C/C++ 混編 -- module.modulemap

背景

Swift project 中 c/c++ 混編一般可以通過創建 bridging-header.h 文件來完成, 然而如果是在 framework 中這種操作是不被準許的, 即使是在 executable target 中雖然能完成集成但是也十分不優雅

方案

使用 modulemap 是目前解決此類問題的主要途徑, 包括c/c++/Objective-c 混編. 關于 modulemap的介紹可以參考 apple 的官方文檔(點我直達). 另外在實際使用中, 我們一般會通過 git submodule 來將需要混編的 libs 集成到項目

使用

  • 集成libs

直接將需要集成的 libs 丟進項目

image.png

  • 創建 module.modulemap 文件

在工程中創建 module.modulemap 文件 (這里直接在 excutable target 下創建) 選擇新建 empty, 文件名填寫 module.modulemap

image.png

  • 編輯 module.modulemap 文件
module Unsafe [system] [extern_c] {
    header "../lib/include/unsafe-header.h"
    export *
}
module SomeModule [system] [extern_c] {
    header "PATH_FOR_HEADER"
    export *
}

Warning: Unsafemodule name, headerpathmodule.modulemap實體路徑(不是 xcode 中看到的虛擬路徑)的相對路徑, 否則會報錯找不到頭文件, Copy Bundle Resources 中不能添加 module.modulemap 文件, 否則第二次編譯會報錯 Redefinition module

image.png

  • 工程配置

    • 方法一: 通過 Configuration Settings File 無疑是最簡單的, 這里不做贅述
    • 方法二: Build Settings -> Import Paths 填寫 $(SRCROOT)/Modulemap (當前 target 文件夾路徑), 如果 libs源碼導入, 報錯各種頭文件找不到, 可以設置下 Building Settings -> Header Search Paths -> $(SRCROOT)/Modulemap/lib/include/
      image.png

      image.png

結束

到這里整個集成便完成了(這里是demo)
注意: 有些 c/c++ source code 的編寫風格可能對編譯器不友好, 導致實際調用的時候報錯, 比如 c++bool 類型, 頭文件沒有直接暴露 struct 的具體實現(只是提供了聲明), 這就需要對 source code 進行改動.

另外 Swift 不支持直接與 Cpp 混編(調用), 實際是通過 C 來完成, 因此 Cheader File 通常要添加如下聲明

#ifdef __cplusplus
extern "C" {
#endif

void entry(); /* Your functions or variables */

#ifdef __cplusplus
}
#endif
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容