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”.

File > New > File…

When Input FILENAME, please check the checkbox of “Also create a header file”.

After the above manipulation, we can get these 3 files automatically by Xcode.

  • C Header File
  • C File
  • Bridging-Header File
#include "ClangTest.h"void testFunc() {    printf("Hello, World!\n");}
#ifndef ClangTest_h#define ClangTest_h#include <stdio.h>void testFunc();#endif /* ClangTest_h */
#import "ClangTest.h"

After these above manipulations, the C function “testFunc()” can be called in the SwiftUI project.

The C Function will run.

--

--

iOS Developer, Front-end Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store