How to call C lang function by SwiftUI
It’s a simple example of the C function with iOS.
Note: This example uses Xcode(Version 12.4) and Target for iOS 14.4
1. Create a new SwiftUI project with Xcode.
In the item “Life Cycle: ”, it doesn’t matter whether “SwiftUI App” or “UIKit App Delegate”.
2. Create the C file in the project.
File > New > File…
3. Check the checkbox of “Also create a header file”
When Input FILENAME, please check the checkbox of “Also create a header file”.
4. Select the “Create Bridging Header” button
5. Then we can get the new 3 files
After the above manipulation, we can get these 3 files automatically by Xcode.
- C Header File
- C File
- Bridging-Header File
6. Write some functions in the “C File”.
#include "ClangTest.h"void testFunc() { printf("Hello, World!\n");}
7. Write Function prototype in “C Header File”
#ifndef ClangTest_h#define ClangTest_h#include <stdio.h>void testFunc();#endif /* ClangTest_h */
8. Write #import “FILENAME.h” in “Bridging-Header File”
#import "ClangTest.h"
After these above manipulations, the C function “testFunc()” can be called in the SwiftUI project.
9. Let’s call the C function in SwiftUI with ButtonView in ContentView.swift
10. Then Run the iOS Simulator
The C Function will run.