I know how to access C libraries in Swift using Xcode on Mac OS, and I know about import Glibc
on Linux, but how can I use a C library like OpenGL with Swift on Linux?
C function pointers are imported into Swift as closures with the C function pointer calling convention, denoted by the @convention(c) attribute. For example, a function pointer that has the type int (*)(void) in C is imported into Swift as @convention(c) () -> Int32 .
Swift is a general purpose, compiled programming language that has been developed by Apple for macOS, iOS, watchOS, tvOS and for Linux as well.
In essence Swift can't consume C++ code directly. However Swift is capable of consuming Objective-C code and Objective-C (more specifically its variant Objective-C++) code is able to consume C++. Hence in order for Swift code to consume C++ code we must create an Objective-C wrapper or bridging code.
To distribute code in binary form as a Swift package, create an XCFramework bundle, or artifact, that contains the binaries. Then, make the bundle available locally or on a server: When you host the binaries on a server, create a ZIP archive with the XCFramework in its root directory and make it available publicly.
Use a System Module to import the OpenGL header file: https://github.com/apple/swift-package-manager/blob/master/Documentation/SystemModules.md
Assuming you have a directory layout like:
COpenGL/
Package.swift
module.modulemap
.git/
YourApp/
Package.swift
main.swift
.git/
the COpenGL/module.modulemap file will look something like:
module COpenGL [system] {
header "/usr/include/gl/gl.h"
link "gl"
export *
}
This has to be created in a separate git repo, with a version tag:
touch Package.swift
git init
git add .
git commit -m "Initial Commit"
git tag 1.0.0
Then declare it as a dependency in YourApp/Package.swift file
import PackageDescription
let package = Package(
dependencies: [
.Package(url: "../COpenGL", majorVersion: 1)
]
)
Then in your main.swift file you can import it:
import COpenGL
// use opengl calls here...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With