Using Swift libraries in Python
So... this is obviously totally, 100%, like for. real. not. supported. by. Apple. …yet?
But still... I thought it was pretty badass. And, seeing how there's already a Swift buildpack for Heroku you could move some slow code into Swift can call it as a library function. But, you know, not in production or anything. That would be silly, right?
Now, having said that, the actual Python/Swift interop may have bugs. I'll leave that as an exercise to the reader.
How to get Python code calling Swift functions:
Get an Ubuntu 15.10 system running. These instructions may also work on other versions of Ubuntu (and Heroku uses Ubuntu server).
sudo apt-get install python-dev
Wherever you put your copy of swift (which you unzipped in the installation instruction)…
cd SWIFT-ROOT/usr/lib/swift/ mkdir python touch module.map
Copy in the contents of the
module.mapfile below (into
TADA! Now you can create the
sit.pyfiles anywhere you want (but in the same directory with each other) and compile them like so:
# creates "libsit.so" (or on OS X, "libsit.dylib") swiftc -emit-library sit.swift
Now this works!
$ python sit.py Hamburger Hamburger Bang! Bang!
Unfortunately there isn't a way to avoid the crazy mangled names in the Python code right now (that I know of). So as you create Swift functions, you'll have to find the mangled name using
nm libsit.so | grep YOUR_SWIFT_FN_NAME
.dylib on OS X. Note: on OS X you get two underscores as a prefix, but you have to remove one for it to work in Python.
One final note… for some reason the mangled names are different on OS X and Linux.