C language call Swift function example

  • 2020-05-26 09:51:24
  • OfStack

Example of calling Swift function in C language

In Apple's official "Using Swift with Cocoa and Objectgive-C" 1 book, details how to use Swift's classes in Objective-C and how to use Objective-C's classes in Swift. The second half also shows how to use the C function in Swift, but nothing is said about how to use the Swift function in C. Here's how to call 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 of the Swift function is related to Blocks syntax 1, which Apple contributes to the Clang compiler. Therefore, we need to import the Swift function into the C language by using the Blocks calling convention. Since it is not possible to directly declare Blocks call convention functions in C, we can do this by defining a global object pointer to Blocks.

Let's create an Swift project on an 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 new Objective-C source file and finally remove it. Here, we must include the header file SwiftTest-Bridging-Header.h in the project.

Then we edit this header file:


extern void (^ __nonnull SwiftFunc)(void);
extern void CFuncTest(void);

The global reference object declared here refers to an Block reference object of type void(^)(void).

Then we 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 in ViewController.swift, edit the following:


//  Here is the SwiftFunc The implementation of the 
private func swiftFuncImpl() {
  print("This is a Swift function!");
}

class ViewController: NSViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()

    //  So here's the definition test.c In the SwiftFunc initialize 
    SwiftFunc = swiftFuncImpl

    //  Here with dispatch_async To test the SwiftFunc Whether or not 1 Straight by hold the 
    dispatch_async(dispatch_get_main_queue()) {
      
      CFuncTest()
    }
  }
}

When the CFuncTest function defined in test.c is called, the SwiftFunc 1Block reference object is called directly from the function, thus achieving the purpose of calling the Swift function in C language.

The above is C language to call Swift function introduction, if you have any questions can leave a message or to the site community exchange discussion, thank you for reading, hope to help you, thank you for the support of the site!


Related articles: