Created
October 7, 2014 21:50
-
-
Save neonichu/dcf49b26a2742404d8f1 to your computer and use it in GitHub Desktop.
Using dlopen / dlsym to call C functions from Swift
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
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) |
This is the actual crash when running the compiled program:
* thread #1: tid = 0x643d, 0x000000010019cde9 libswiftCore.dylib`_swift_retain_(swift::HeapObject*) + 9, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
frame #0: 0x000000010019cde9 libswiftCore.dylib`_swift_retain_(swift::HeapObject*) + 9
libswiftCore.dylib`_swift_retain_(swift::HeapObject*) + 9:
-> 0x10019cde9: lock
0x10019cdea: addl $0x4, 0x8(%rdi)
0x10019cdee: movq %rdi, %rax
0x10019cdf1: popq %rbp
(lldb) bt
* thread #1: tid = 0x643d, 0x000000010019cde9 libswiftCore.dylib`_swift_retain_(swift::HeapObject*) + 9, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
* frame #0: 0x000000010019cde9 libswiftCore.dylib`_swift_retain_(swift::HeapObject*) + 9
frame #1: 0x000000010000199b FunctionPointer`top_level_code + 2459
frame #2: 0x0000000100001a5a FunctionPointer`main + 42
frame #3: 0x00007fff8af265c9 libdyld.dylib`start + 1
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
😭