Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 146 ยท Advanced Swift

Interoperating with C

Call C libraries from Swift: how C types map to Swift, C strings, pointers, errno, structs, callbacks with @convention(c), and the pitfalls that crash programs.

Swift was designed to live next to C. Every operating system API on Linux, macOS and Windows is ultimately a C API, and thousands of libraries (SQLite, zlib, OpenSSL, libcurl) are written in C. Swift can call all of them directly, with no wrapper code and no foreign-function layer: you import a module, and the C functions, structs, enums and constants simply appear as Swift declarations. The compiler reads the C headers for you.

This lesson shows what that looks like in practice, using the C standard library that is already available on the site's runner. You will learn how C types map to Swift, how to pass strings and buffers across the boundary, how to read errno, how to handle C structs and callbacks, and where the safety net of Swift ends. If you have not read Memory Layout and Unsafe Swift, skim them first: C interop is mostly unsafe pointers.

Everything in the TryIts runs on Linux (glibc). import Foundation re-exports the C library (Glibc on Linux, Darwin on Apple platforms), so strlen, qsort or open are available after that single import. You can also write import Glibc explicitly, but that line would not compile on a Mac, so portable code uses Foundation.

Calling your first C function

When you import a module, the compiler turns each C declaration into a Swift one. The rules are mechanical, and once you know them you can read any C header as Swift:

  • int becomes Int32 (also spelled CInt), long becomes Int (CLong; 64 bits on 64-bit Linux), char becomes Int8 (CChar), double becomes Double, size_t becomes Int.
  • Pointers become UnsafePointer<T> (const) and UnsafeMutablePointer<T>; void * becomes UnsafeRawPointer and UnsafeMutableRawPointer.
  • A pointer that may be NULL becomes an optional pointer. That is how Swift's null safety survives the crossing.
  • Function names and parameter order stay exactly as in C. There are no argument labels, because C has none.
  • Integer constants defined with #define and simple enums arrive as constants; function-like macros do not arrive at all.
Swift Calling the C standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints 5. abs works on Int32 while labs takes a long, so you see 5 7. strtol parses the digits of "123abc" and stops at the first invalid character, so you get 123. The sizes 4 8 1 8 show that CInt is 4 bytes while CLong is 8 bytes on this 64-bit platform. The C standard does not fix those sizes, which is why Swift gives you the aliases CInt, CLong, CChar and friends: use them when you declare something that must match a C signature, and use plain Int everywhere else.

Notice what Swift did for you: you passed a Swift String literal where strlen wants a const char *. A Swift String converts automatically to a temporary, NUL-terminated C string for the duration of the call. That convenience only works for arguments of type UnsafePointer<CChar>; the sections below explain the cases where you must do the work yourself.

Types do not mix

C functions take exactly the types they declare, and Swift never converts integers implicitly, so a C call is where you meet explicit conversion most often. labs wants an Int, and giving it an Int32 is an error:

Swift No implicit integer conversion (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: cannot convert value of type 'Int32' to expected argument type 'Int'. The fix is labs(3) (the literal adapts to Int) or an explicit Int(someInt32). When a C API takes int and you have an Int, write Int32(clamping: value) or Int32(exactly: value) rather than Int32(value) if the value could be out of range; the plain initializer traps on overflow.

C strings

A C string is a pointer to bytes that end with a zero byte. Swift has three common ways to cross that boundary.

Swift to C: pass a String directly, or use withCString. The pointer is valid only inside the closure (or during the call). Never store it.

C to Swift: String(cString:). It copies the bytes up to the NUL into a new Swift string, decoding UTF-8. After the copy the C memory is yours to free if you own it.

Ownership is the hard part. A function like strdup returns memory allocated with malloc. Swift does not know about it, ARC does not manage it, and you must call free exactly once.

Swift Copying, owning and formatting C strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get swift, then Swift (we changed the C copy), and the original Swift string is still swift. The accent line prints 5 6 6: five characters, but six UTF-8 bytes, and strlen counts bytes, never characters. vsnprintf writes into your buffer and returns the length, 10, so the last line shows 10 n=42 x=3.5.

That last call also hides a limit. C functions with a variable argument list (printf, sprintf, scanf) cannot be called from Swift. Swift offers the va_list variants instead, which take a CVaListPointer that you build with withVaList. Try the direct call to see what the compiler says:

Swift Variadic C functions are unavailable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The real error is error: 'printf' is unavailable: Variadic function is unavailable, followed by a note pointing at the declaration in /usr/include/stdio.h. In your own programs, use print, string interpolation or String(format:) instead of printf; they are safer, because a wrong format specifier in C is undefined behavior.

Never keep a pointer from withCString or withUnsafeBufferPointer after the closure returns. Swift may have made a temporary copy, and the memory disappears when the closure ends. Escaping a pointer compiles fine and fails later in ways that look random. If C needs the string to live longer, make your own copy with strdup and free it when the library says it is done.

Pointers, buffers and optionals

C APIs love buffers: a pointer plus a count. Swift arrays bridge to them with withUnsafeBufferPointer (read) and withUnsafeMutableBufferPointer (write). A Swift array can also be passed directly where a C function expects const T * or, with &, T *. The classic example is qsort, which sorts a raw block of memory using a comparison callback. Look at how void * shows up as UnsafeRawPointer?:

Swift qsort, malloc and optional pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The array comes back sorted as [1, 2, 5, 7, 9], and the second part prints Optional<UnsafeMutableRawPointer> followed by [0, 1, 4, 9]. Three details are worth remembering:

  • baseAddress is optional, because an empty array has no storage. The ! is safe only when you know the buffer is not empty; production code checks count first.
  • malloc returns an optional raw pointer, because it can return NULL. bindMemory(to:capacity:) tells Swift to treat those bytes as Int32 values, after which you can index the pointer like an array.
  • Memory from malloc is released with free, memory from Swift's allocate with deallocate. Mixing them is undefined behavior.

The most frequent compile error in C interop is forgetting that nullable results are optional. Passing the result of strdup straight to another function fails:

Swift Forgetting that C can return NULL (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says error: value of optional type 'UnsafeMutablePointer<CChar>?' (aka 'Optional<UnsafeMutablePointer<Int8>>') must be unwrapped to a value of type 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>') and offers ?? and ! as fixes. This is Swift doing its job: strdup really can return NULL when memory runs out, so use guard let p = strdup("abc") else { ... } or accept the crash of ! when running out of memory is unrecoverable for your program anyway.

Errors: errno and return codes

C has no exceptions. Functions return a sentinel (-1, NULL, a negative code) and set the global errno. Swift code that calls C should translate those signals into Swift throws at the edge, so the rest of the program uses normal error handling (see Error handling). Below is a complete round trip with the POSIX file API: open, write, read, close, unlink, plus a failing open and a pipe:

Swift POSIX files, errno and a pipe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output starts with true (the descriptor is valid) and 22, the number of bytes written. Reading them back prints 22 written with write(2). After unlink removed the file, access returns -1 and errno == ENOENT is true, so the next line is -1 true. The failing open returns -1, errno is 2, and strerror turns that into No such file or directory. Finally pipe returns 0 and the four bytes sent through it print as ping.

Two rules protect you here. Read errno immediately after the failing call, because any other C call (including print) may overwrite it. And remember it only means something when the function reported failure; after a successful call it can hold a stale value from earlier. A clean wrapper looks like this:

Swift
// read-only example: a typical wrapper that turns errno into a Swift error
struct POSIXError: Error { let code: Int32 }

func openFile(_ path: String) throws -> Int32 {
    let fd = open(path, O_RDONLY)
    if fd < 0 { throw POSIXError(code: errno) }
    return fd
}

Foundation also has its own POSIXError type and POSIXErrorCode; on Apple platforms and Linux you can throw POSIXError(POSIXErrorCode(rawValue: errno)!). For everyday file work you will not need any of this, because FileManager wraps these calls for you. Dropping to open and read makes sense for file descriptors, sockets, pipes and anything else Foundation does not model.

C structs, enums and constants

Imported C structs become Swift structs with a memberwise initializer that takes every field, and a zero initializer with no arguments. C arrays inside structs arrive as tuples, which is awkward but workable. Enums and #define constants arrive as constants whose type is the C type (Int32 for most flags). Here is struct tm from <time.h>, a typical C struct with many fields:

Swift Using struct tm, timegm and strftime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints 1768478400 (noon UTC on 15 January 2026), then 4 14: Thursday (0 is Sunday) and the 14th day of the year counted from zero. strftime returns 16, the number of characters written, and the text is 2026-01-15 12:00. The remaining lines show the timeval fields, the sizes 56 and 16 bytes, and div_t(quot: 1, rem: 2), which is a C struct printed by Swift's default description.

Three conventions to notice:

  • &parts passes a Swift variable as a mutable pointer for the duration of the call. The compiler creates a valid temporary pointer, so there is no unsafe allocation. This is the most common and safest style of out-parameter.
  • Swift fills structs field by field. C code often expects zeroed memory, so the empty initializer (tm()) is what you want.
  • Layout follows the C rules exactly for imported structs. Unlike pure Swift types, an imported struct's layout is a stable contract, which is why you can hand it to C.

Callbacks: @convention(c)

Many C APIs take a function pointer: qsort for a comparison, signal for a handler, pthread_create for a thread body. In Swift, the type of such a parameter is @convention(c) (Args) -> Result. A closure can be passed there only if it captures nothing, because a C function pointer is a bare code address with no room for captured variables. Referring to a top-level function or a literal closure that uses no local state works.

How do you give the callback access to your data? The C convention is a context pointer: an extra void * parameter that the library passes back to you unchanged. In Swift, Unmanaged converts a class instance into such a pointer and back:

Swift A C callback with a context pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see [0, 1, 4, 9], then [1.25, 2.0, 3.5], then true for the binary search. passUnretained does not change the reference count, so box must stay alive for as long as C may call back, which it does here because box is a global. If the callback outlives the current scope, use passRetained and balance it with release().

Swift would normally reject a capturing closure with a clear diagnostic. On this server's compiler build, a @convention(c) closure that captures a local variable even crashes swiftc (an internal assertion failure in the data-race checker) instead of printing a message, so the lesson does not run that case. Treat it as a compiler bug and use the context-pointer pattern above. The captures you may write are global constants and global functions.

Using your own C code and C libraries

On the runner you have one main.swift file and the system C library, nothing more. In a real project, you reach other C code in one of two ways. These snippets need build tools (SwiftPM or swiftc flags), so they are read-only.

A system library via a module map. A module.modulemap tells the compiler which header defines a module. With SwiftPM you declare a .systemLibrary target; the file looks like this:

TEXT
// read-only example: Sources/CSqlite/module.modulemap
module CSqlite [system] {
    header "shim.h"
    link "sqlite3"
    export *
}

After that, import CSqlite brings in every function in shim.h. Packages such as SwiftNIO and swift-crypto ship their own C targets in the same way.

Your own C source files. A SwiftPM target that contains .c files and an include/ folder with headers is a C target. Other Swift targets import it by name. Add __attribute__((swift_name("..."))) and NS_SWIFT_NAME-style annotations in the header to rename functions so they read like Swift.

The opposite direction (C calling Swift) uses @_cdecl, an underscored and therefore unofficial attribute that gives a Swift function a C symbol name:

Swift
// read-only example: exporting a Swift function to C code
@_cdecl("swift_add")
public func add(_ a: Int32, _ b: Int32) -> Int32 {
    a + b
}

Because the attribute is underscored, it is not part of the stable language, so check the toolchain you target before relying on it.

Good habits for C interop

  • Wrap the C layer once. Keep the unsafe code in a small type, expose a safe Swift API (throws, value types, Sequence), and let nothing else touch pointers.
  • Match ownership rules in code. Document who allocates and who frees. Use defer right after allocation so cleanup happens on every path (defer and cleanup).
  • Prefer withUnsafe... closures to long-lived pointers. They make the pointer's lifetime visible.
  • Check every return code. C will not throw; a forgotten -1 becomes a bug three calls later.
  • Do not read errno late. Capture it in a local right after the failure.
  • Convert types deliberately. Use Int32(clamping:), Int(exactly:) and the C type aliases at the boundary.
  • Beware of lifetimes. An object whose pointer you handed to C must stay alive; withExtendedLifetime(_:_:) exists for exactly that.
  • Test with large and empty inputs. Empty arrays have no baseAddress, and long strings exceed small fixed buffers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Swift represent a C pointer that may be NULL?

    Nullability is part of the Swift type: a pointer that C may return as NULL arrives as an optional, so you must unwrap it before using it.
  2. 2. What does CInt stand for on the site's 64-bit Linux runner?

    CInt is the alias for the Swift type that matches the C int, which is Int32 (4 bytes). CLong is 8 bytes on this platform.
  3. 3. Why does calling printf("%d\n", 42) fail to compile?

    The compiler reports that printf is unavailable because it is variadic. vsnprintf with withVaList, String(format:) or plain print are the Swift ways.
  4. 4. When is it safe to read errno?

    errno is a global that any later C call (including those hidden in print) can change, and it is only meaningful after a call that signalled an error.
  5. 5. How do you give a @convention(c) callback access to your own Swift data?

    A C function pointer cannot carry captured state, so C APIs pass a void * context back to the callback; Unmanaged.toOpaque() and fromOpaque(_:) convert a class instance to and from it.

Summary

  • Importing Foundation (or Glibc) makes the C standard library available; C declarations appear as Swift functions with the same names and no argument labels.
  • C types map to Int32/CInt, Int, CChar, Double and so on, and Swift never converts between them implicitly.
  • A char * converts from a Swift String for the duration of a call; use String(cString:) to copy C text into Swift and strdup/free for memory you own.
  • Nullable C pointers are optionals, void * is a raw pointer, and &variable passes a temporary pointer for out-parameters.
  • Variadic functions such as printf are unavailable; use print, String(format:) or the va_list forms.
  • Check return codes and read errno right after a failure, then convert it into a Swift error at the boundary.
  • C structs import with memberwise and zero initializers; callbacks use @convention(c) closures that capture nothing, with a context pointer for state.
  • Module maps and C targets (read-only here) bring your own C libraries in; wrap them in a small safe Swift layer.

Next: Dynamic Features