Bare minimum to use a C function from Swift

Googling around, I found several blog entries, some old and no longer valid it seems, that attempt to explain how to use a C library from Swift. Doing so appears to involve a lengthy process or creating a wrapper and a bunch of files.

However I just want to use a single C function, not a library, and I'm coming at this from the point of view that Swift Should Do It Right, instead of the alternative position that Swift Should Be Unnecessarily Complex.

Therefore I am wondering why all this wrapper business is even necessary. Is there perhaps a simpler, more minimalist way to call a C function from Swift? Suppose I don't even have a library, I have just a .c file or its compiled .o file.

I just need to

  1. tell swiftc what the prototype for the C function is.
  2. call the function from Swift
  3. link these on the command-line.

How to do that?

This StackOverflow question sounds similar and the accepted answer is up to date (as of 2019‐01‐23). Does it contain what you want to know?

bla.swift:

laber()

laber.h:

void laber();

laber.c:

#include <stdio.h>
void laber() {
        printf("Laber\n");
}

Makefile:

all: bla
	@./bla
clean:
	rm -f bla laber.o
bla: bla.swift laber.h laber.o
	swiftc -import-objc-header laber.h bla.swift laber.o -o bla
laber.o: laber.c
	clang -c laber.c

Output from 'make':

Laber
5 Likes

Thanks. Now, what if I wanted to use a C library functions e.g. puts?
e.g.

func foo () {
puts ("abcef".UTF8String)
}

In the case of puts, it's in the C standard library, so you should be able to import the C standard library module for your platform (import Darwin on Apple platforms, or import Glibc on Linux). You can also pass Swift string literals directly as C char* arguments:

import Glibc

func foo() {
  puts("abcef")
}

Another possibility is to include stdio in laber.h:

#include <stdio.h>

You could also import it from Foundation. Either with import Foundation or import func Foundation.puts, then you don't have to worry about which platform you're on.