Skip to content

Instantly share code, notes, and snippets.

@neonichu
Created October 7, 2014 21:50
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save neonichu/dcf49b26a2742404d8f1 to your computer and use it in GitHub Desktop.
Save neonichu/dcf49b26a2742404d8f1 to your computer and use it in GitHub Desktop.
Using dlopen / dlsym to call C functions from Swift
import Darwin
let handle = dlopen("/usr/lib/libc.dylib", RTLD_NOW)
let sym = dlsym(handle, "random")
let functionPointer = UnsafeMutablePointer<() -> CLong>(sym)
let result = functionPointer.memory()
println(result)
@kjunichi
Copy link

Hello! Thanks your code.I made it work.

import Darwin

let handle = dlopen("/usr/lib/libc.dylib", RTLD_NOW)
let sym = dlsym(handle, "random")

typealias randomFunc = @convention(c) () -> CInt
let f = unsafeBitCast(sym, randomFunc.self)
let result = f()
dlclose(handle)
print(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment