Overview
Swift code can all functions written in C. This page describes the steps to create a SwiftUI app that includes C code and calls its functions.
Steps
-
Create a new Xcode project where the interface is “SwiftUI” and the language is “Swift”.
-
Select File … New … File (or press cmd-n).
-
In the “Source” category, select “C File”.
-
Enter a name for the file without a file extension.
-
Check the “Also create a header file” checkbox.
-
Click the “Next” button.
-
Click the “Create” button.
-
In the dialog that appears, click the “Create Bridging Header” button.
-
In the generated header file, enter the signatures of the functions you will define. For example:
long factorial(int n); -
In the generated C file, enter the function definitions. For example:
long factorial(int n) { if (n == 0 || n == 1) return 1; return n * factorial(n-1); } -
In the generated
SwiftUICallsC-Bridging-Header.hfile, add import directives for each of your C header files. For example:#import "factorial.h" -
Call the C functions in Swift source files. For example,
ContentView.swiftcould contain the following:Text("Factorial is \(factorial(5)).") // 120
Libraries
To use a C library from Swift:
- Build a version of the C library that is compatible with iOS.
- Create a group within the Xcode project named “include”.
- Copy the
.hfiles for each library into this directory. - Create a group within the Xcode project named “lib”.
- Copy the
.afiles for each library into this directory. - Select the top entry in the project navigator.
- Select the project.
- Select the “Build Settings” tab.
- Open the “Search” section.
- Open the “Header Search Paths” entry.
- In the “Release” section, add the string “include”.
- Open the “Library Search Paths” entry.
- In the “Release” section, add the string “lib”.
Invoking Lua
For details on the Lua programming language, see Lua. This contains details on starting the Lua virtual machine from C and deciding which standard libraries should be loaded. For example, by not loading the “os” library, Lua code is unable to read or write files.
- Build a version of Lua that is compatible with iOS.
See lua-iosx.
Enter the following commands to generate
the directory
frameworks/lua.xcframework:git clone -b 5.4.4 https://github.com/apotocki/lua-iosxcd lua-iosxscripts/build.sh
- Create a “Frameworks” group.
- Drag the
lua-ios/frameworks/lua.xcframeworkdirectory into the group. - In the dialog that appears, check the “Copy items if needed” checkbox and click the “Finish” button.
It is now possible to call functions from the Lua C API from functions defined in C source files. Those C functions can be called from Swift code.
For an example of embedding the Lua interpreter in a SwiftUI application, see Swift Calling C and the GitHub respository SwiftUICallsC.