Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Interoperating Golang with Swift

Interoperating Golang with Swift

CGO
objc-header

Avatar for swt02026

swt02026

August 06, 2019
Tweet

More Decks by swt02026

Other Decks in Programming

Transcript

  1. 大綱 ▪ 了解 ABI 與 Linker & Loader 行為 ▪

    使用 CGO 產出符合 C ABI 的 Header 和 Library ▪ 在編譯 Swift 程式時,引入 Objective C Header 和 Library ▪ 反過來做? ▪ 其他語言?
  2. ABI ▪ Object File 中描述變數、函數執行的行為 ▪ Name Mangling (Symbol) ▪

    System Call 參數擺放 ▪ Function Call 參數擺放 ▪ Data Type Alignment and Size ▪ Object File Layout (ELF、COFF、Mach-O) ▪ 目前只有 C ABI 較穩定 Application Binary Interface Object File Syscall Function Call Data Type Symbol
  3. Linker & Loader ▪ Linker 將許多 Object File 連結在一起(Linking) ▪

    Linking 依照 Symbol Resolving 的時機分為 ▪ Static Linking ▪ Dynamic Linking ▪ Linker 在 Object File 加上載入記憶體所需資訊 (Relocation、Section、Permission) ▪ Loader 依照 Object File 中描述資訊,將程式載入 記憶體中 Object File Object File Relocation Section Permission Linking Memory Loading
  4. CGO ▪ 提供 C ABI 與 Golang 之間溝通橋樑 ▪ C

    Calling Golang Library By C ABI ▪ Golang Wrapper for C ▪ 執行 go build -buildmode=c-shared 產出 ▪ 符合 C ABI 的 Shared Object (.so) ▪ Header File (.h) C CGO Golang
  5. swiftc ▪ 利用 Objective C 相容 C/C++ 的特性做為 Bridge ▪

    將 cgo 產出的 Header import 進來 ▪ 執行產生的執行檔,與 cgo 產出的 Shared Library 進行 Dynamic Linking,即為呼叫 go Library 參數 -import-objc-header C Header Shared Library Swift Source Execute File Go Source
  6. Golang Call Swift ▪ 將 Swift 編譯成相容 C ABI (@asmname)

    的 Library ▪ -emit-objc-header ▪ -emit-objc-header-path ▪ 使用 cgo 將 swift 產出的 Library 做成 Golang Wrapper ▪ 在 GO 程式中進行呼叫
  7. Java、Scala、Kotlin ▪ 使用 Java Native Interface ▪ 使用 JVM API

    ▪ GraalVM ▪ Substrate Machine ▪ Truffle Framework(sulong) ▪ Scala Native ▪ Kotlin Native ▪ JDK 13 Parama
  8. Python、Ruby、Julia、 NodeJS、R、Lua ▪ C/C++ Plugin System ▪ gyp ▪ Rcpp

    ▪ Cython ▪ C FFI ▪ GraalVM ▪ Truffle Framework(sulong)