Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a C library in Swift on Linux

Tags:

linux

swift

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?

like image 650
Patrick Avatar asked Dec 07 '15 10:12

Patrick


People also ask

Can you use C in Swift?

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 .

Can you program Swift on Linux?

Swift is a general purpose, compiled programming language that has been developed by Apple for macOS, iOS, watchOS, tvOS and for Linux as well.

Can Swift use C++ libraries?

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.

How do you distribute Swift library?

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.


1 Answers

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...
like image 179
Mike Buhot Avatar answered Sep 21 '22 17:09

Mike Buhot