Wrapping unsafe legacy C APIs in modern and idiomatic Swift for fun and profit!

updated over 1 year ago; latest suggestion over 1 year ago

The world is built upon legacy libraries written in C.

While many of these time-tested libraries are well-engineered and maintained, they tend to be tedious and brittle to use by modern standards. There are raw pointers all over the place. Often void pointers that are waiting to be cast to arbitrary data types, always at risk of corrupting memory. Memory that, to add insult to injury, needs to be managed manually. With errors being often no more than an arbitrary integer constant, documented somewhere, if you're lucky. Footguns all the way down.

We will take a detailed look at methods for turning such inherently unsafe legacy APIs into native first-class citizens in Swift, by example of a Swift package of mine that wraps LMDB, a popular key-value store written in C.

The talk will cover topics such as:

  • preventing API-misuse through expressive types and generics.
  • eliminating conflicts by lifting bitfield-based legacy configs into safe and expressive types.
  • type-safe API specialization by smart use of generics and Phantom Types.
  • wrapping database-cursors with idiomatic and safe Swift iterators.
  • encapsulating raw memory access through Unsafe…Pointer.

Instead of something like this: https://gist.github.com/anonymous/070bd75d1d186e4f45ce0b196455ca95

… we will be able to do this: https://gist.github.com/anonymous/55acf049b2371f8f9883f7aedba34041


  • 8b2f2d3e6553c2b4048b93300959895ab76b4154?size=100x100 8b2f2d3e6553c2b4048b93300959895ab76b4154 suggests over 1 year ago

    I'm sure you already know this, but this task is really not for the faint of heart. Wrapping a library and providing even a moderately tolerable API requires deep understanding of the original library and it's design goals and limitations. Plus API design is a skill some practise with only indifferent success.

    That said, I'm sure this is a task many could benefit from even if only in their own projects.