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

前端 未结 2 1754
挽巷
挽巷 2020-12-03 06:23

Is there a way to call a C function loaded from a dylib from Swift?

This is my dylib file:

cppdemofile.cpp

#include \"cppdem         


        
相关标签:
2条回答
  • 2020-12-03 06:44

    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)
    }
    
    0 讨论(0)
  • 2020-12-03 06:48

    In order to use C++ code in Swift, you need to wrap it in C functions or Objective-C classes.

    Also see Call a C++ function from Swift

    0 讨论(0)
提交回复
热议问题