[swift-users] C/FFI interop

Brent Royal-Gordon brent at architechies.com
Wed Dec 23 17:18:22 CST 2015

> What are the current facilities planned or in development for FFI? Just as Swift functions can be exposed through @objc, how would I add a similar capability for pure C? Is this what, in fact, module maps might be for?
> I ask since writing high performance native code for dynamic languages is currently done in C, and that’s a pretty bad idea. It would be great for Swift if people started writing native bindings in it as opposed to C, but it probably needs at the least a way to re-export global public functions for C/C++.
> Please let me know if I should take this to swift-dev or swift-evolution!

Swift does not require a foreign function interface—it can directly call C functions. Sometimes Swift generates a trampoline to do this, but often not even that. The module map basically just tells Swift which headers and binaries make up a particular module. There's generally no need to write any bridging code—it just works.

There are a few C constructs that Swift doesn't support very well, like unions and fixed-size arrays in structs. In those cases, you may need to write some C functions which perform the operations that can't be easily expressed in Swift, but these functions would just be plain old C with no special bridging involved. Similarly, you may choose to write wrappers around some of your library's C constructs to make them more convenient to use—for instance, if your library has a struct called `foo` and an operation on that struct called `frobnicate_foo()`, you might extend `foo` to add a `frobnicate()` method to it. But this is purely optional, and you would write it in plain old Swift.

Though Apple's platforms are most commonly associated with Objective-C, there's a lot of C over there too. Swift works very well with it—this stuff is fast, as transparent as it can be, and frequently exercised.

In short: Just try it. It's pretty easy.

Brent Royal-Gordon

More information about the swift-users mailing list