Friday, January 23, 2026

Improving the Usability of C Libraries in Swift

Doug Gregor:

The Swift code above has a very “C” feel to it. It has global function calls with prefixed names like wgpuInstanceCreateSurface and global integer constants like WGPUStatus_Error. It pervasively uses unsafe pointers, some of which are managed with explicit reference counting, where the user provides calls to wpuXYZAddRef and wgpuXYZRelease functions. It works, but it doesn’t feel like Swift, and inherits various safety problems of C.

Fortunately, we can improve this situation, providing a safer and more ergonomic interface to WebGPU from Swift that feels like it belongs in Swift. More importantly, we can do so without changing the WebGPU implementation: Swift provides a suite of annotations that you can apply to C headers to improve the way in which the C APIs are expressed in Swift. These annotations describe common conventions in C that match up with Swift constructs, projecting a more Swift-friendly interface on top of the C code.

[…]

The problem of needing to layer information on top of existing C headers is not a new one. As noted earlier, Swift relies on a Clang feature called API notes to let us express this same information in a separate file, so we don’t have to edit the header.

Previously:

1 Comment RSS · Twitter · Mastodon


Never mind that—how do you call Swift-native API in C (without cooperation from the Swift code and/or tedious linking to the ABI, obviously)? I hate to burden my Swift-loving friends with my appalling preference for archaic and insecure languages, but sometimes you gotta do what you gotta do, and increasingly Apple's API is now Swift-only, including stuff that should certainly have C interface like testing APFS filesystem flags.

Leave a Comment