Skip to content

Instantly share code, notes, and snippets.

@jerrymarino
Created June 17, 2018 04:06
Show Gist options
  • Save jerrymarino/b77c335ea54c934eb0c9198a4858d496 to your computer and use it in GitHub Desktop.
Save jerrymarino/b77c335ea54c934eb0c9198a4858d496 to your computer and use it in GitHub Desktop.
How to call Swift functions by address
func helloWorld(a: Int) {
print("Hello world!", 1)
}
// Converting to an address:
// - Erase the type to an Object so swift doesn't complain
// - Bitcast
var erasedFunc = helloWorld as AnyObject
let address = unsafeBitCast(erasedFunc, to: Int.self)
// Next get a Pointer, which is callable in other contexts
let funcPtr = UnsafePointer<Any>.init(bitPattern: address)
// To call in Swift, simply cast back to the original type
let castedFunc = unsafeBitCast(funcPtr, to: AnyObject.self)
let cb = castedFunc as? ((Int) -> Void)
cb!(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment