Swift: How to call a C function loaded from a dylib

Calling the add function from Swift is possible because you
defined it to have C linkage with extern "C".

Making the library a Swift module (as suggested by jtbandes in above
comments) might be the better solution,
but here is how you can use the function pointer return by dlsym() from Swift:

First add

typedef int(*addFunc)(int, int);

to the bridging header file, or alternatively define

typealias addFunc = @convention(c) (CInt, CInt) -> CInt

in Swift. Then the following works:

let handle = dlopen(path, RTLD_NOW)
if (handle != nil) {
    var sym = dlsym(handle, "add")
    if (sym != nil) {
        let f = unsafeBitCast(sym, addFunc.self)
        let result = f(12, 45)
        print(result)
    }
    dlclose(handle)
}

Of course this will crash if addFunc does not match the
actual signature of the loaded function.


Update for Swift 3:

if let handle = dlopen(path, RTLD_NOW) {
    if let sym = dlsym(handle, "add") {
        let f = unsafeBitCast(sym, to: addFunc.self)
        let result = f(12, 45)
        print(result)
    }
    dlclose(handle)
}

Leave a Comment