Swift C call shortcut?

Others have discussed how to call C code from Swift and it works well. Others have also discussed how calling Swift as a subroutine in C code is a bad idea, because the entire Swift runtime will need to be configured.

But here's my question: If my program is based on Swift and calls C routines, but I would like to provide callbacks for those routines, is it possible? And could these C routines call Swift routines by name, provided they took C-compatible typed parameters (CInt, etc.)?

Also, can C and Swift share variables? In any direction?

+3


source to share


1 answer


The approved way to do this is to assign swift functions / closures to C function pointers.

But if you look at the Swift source code, it uses the undocumented attribute @_silgen_name

in several places to provide swift C functions, 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 that it is undocumented, you probably don't want to use it, and it is a little somber about what functions and parameter types will work. Is ABI resilience anyone?

+2


source







All Articles