这可行(在XCode 9 beta中测试) main.c //声明函数.您可能会将其放在.h中int mySwiftFunc(int);int main(int argc,const char * argv []){int retVal = mySwiftFunc(42);//调用swift函数printf(你好,来自C:%d",retVal);返回0;} SomeSwift.swift @_ silgen_name("mySwiftFunc")//为函数指定C名称public func mySwiftFunc(number:Int)->诠释{print(您好,来自Swift:\(number)")返回69} 但是考虑到它没有文档,您可能不想使用它,并且它可以使用哪些函数签名和参数类型有些模糊.ABI稳定的人吗?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 whole Swift runtime would need to be set up.But here's my question: if my program is based in Swift, and calls C subroutines, but would like to provide callbacks for those subroutines, is that possible? And could those C subroutines call Swift routines by name, provided that they took C compatible typed parameters (CInt, etc)?Also, can C and Swift share global variables? In either direction? 解决方案 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 .hint 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 namepublic 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?? 这篇关于Swift调用C调用Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!