How do I call Go from Swift/Kotlin and vice versa?

Calling Go from Swift or Kotlin (and vice versa) involves using Foreign Function Interface (FFI) techniques, which allow different programming languages to communicate with each other. Below, you'll find an overview of how to achieve this with examples.

Go, Swift, Kotlin, FFI, foreign function interface, interlanguage communication
This guide covers how to call Go functions from Swift and Kotlin and how to invoke Swift or Kotlin functions from Go. Examples provided will illustrate the essential steps for setting up these inter-language calls.

Calling Go from Swift


// Example Go code
package main

import "C"

//export Add
func Add(a, b int) int {
    return a + b
}

func main() {}
    

Calling Swift from Go


// Example Swift code
@_exported import MyGoLib

let result = MyGoLib.Add(3, 4)
print(result) // Outputs 7
    

Calling Kotlin from Go


// Example Kotlin code
fun add(a: Int, b: Int): Int {
    return a + b
}
    

Calling Go from Kotlin


// Example Go code to expose a function
package main

import "C"

//export Add
func Add(a, b int) int {
    return a + b
}

func main() {}
    

Go Swift Kotlin FFI foreign function interface interlanguage communication