The use of Swift's classes in Objective-c and the use of classes in Objective-c in Swift are described in detail in Apple's official using Swift with Cocoa and Objectgive-c. The latter section also describes how to use the C function in Swift, but nothing is said about how to use the Swift function in the C language. Here I will share with you how to invoke the Swift function in the C language.
The first thing we need to know is that all swift functions belong to closures. Second, the calling convention for swift functions is consistent with the blocks syntax that Apple contributes to the clang compiler. Therefore, we need to import swift functions into the C language by using the blocks calling convention. Since the functions of the blocks calling convention cannot be directly declared in C, we can do so by defining a global pointer to the blocks object.
Below we create a swift project on a MacOS system called Swifttest. Then create a new C source file named TEST.c, if Xcode does not pop up whether to create a new Bridging-header file, then we can add a objective-c source file, and finally remove it. Here, we must include Swifttest-bridging-header.h this header file in the project.
Then we edit this header file:
extern void __nonnull Swiftfunc) (void);
extern void Cfunctest (void);
The global pointer to a block of type void (^) (void) is declared here as a reference object.
And then we'll look at the test.c source file:
void (^swiftfunc) (void) = NULL; void Cfunctest (void) { swiftfunc ();}
We define the Swiftfunc global object and initialize it to null.
Then edit the following in Viewcontroller.swift:
//here is the realization of the SwiftfuncPrivatefunc Swiftfuncimpl () {print ("This is a Swift function!");}classViewcontroller:nsviewcontroller {Overridefunc viewdidload () {super.viewdidload ()//This initializes the Swiftfunc defined in the test.cSwiftfunc =Swiftfuncimpl//here, use Dispatch_async to test whether the Swiftfunc has been holding.Dispatch_async (Dispatch_get_main_queue ()) {cfunctest () }}}
When the Cfunctest function defined in test.c is called, the function calls the Swiftfunc block reference object directly, thus achieving the purpose of invoking the function in Swift in the C language.
How to call the Swift function in the C language