Created
June 17, 2018 04:06
-
-
Save jerrymarino/b77c335ea54c934eb0c9198a4858d496 to your computer and use it in GitHub Desktop.
How to call Swift functions by address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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