Swift call C call Swift?

后端 未结 1 418
無奈伤痛
無奈伤痛 2021-01-13 06:03

Others have discussed how to call C code from Swift, and it works nicely. Others have also discussed how calling Swift as a subroutine to C code is a bad idea, because the w

相关标签:
1条回答
  • 2021-01-13 07:05

    The approved way to do this kind of thing is assigning swift functions/closures to C function pointers.

    But if you look at the Swift source code, it uses the undocumented @_silgen_name attribute in several places to give swift functions C compatible names, so they can be called directly from C and C++

    So this works (tested in XCode 9 beta)

    main.c

    // declare the function. you would probably put this in a .h
    int mySwiftFunc(int);
    
    int main(int argc, const char * argv[]) {
    
        int retVal = mySwiftFunc(42); // call swift function
        printf("Hello from C: %d", retVal);
    
        return 0;
    }
    

    SomeSwift.swift

    @_silgen_name("mySwiftFunc") // give the function a C name
    public func mySwiftFunc(number: Int) -> Int
    {
        print("Hello from Swift: \(number)")
        return 69
    }
    

    But given it's undocumented you probably don't want to use it, and it's a bit murky on what function signatures and parameter types it will work with. ABI stability anyone??

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