I thought I’d write about something that I feel people are a bit too scared of doing, which is binding a foreign library into their favourite language. We all have our own strange favourite language in which programming comes out more naturally, faster and more correctly. However, I sometimes found myself hitting bumps when I wanted to use a certain awesome library that is programmed in a different language, and usually compiled to native binary libraries.
The usual approach is to search for bindings existing for the language, and usually there will already have been someone who made the bindings, neatly packaged them and released them for you to use. The problem occurs when there are no such bindings available, which happens more frequently for less mainstream languages (like my beloved Common Lisp). Sometimes there are some incomplete bindings that someone posted, which don’t cover all the cases. However bindings are fairly easy to do, even though they are not that easy to structure properly.
In fact, invoking and getting values back is the easier part, usually you just use some built-in construct to invoke the native procedure, and the FFI takes care of the low-level bindings, and sometimes even memory management. However, in order to feel like it is part of the language, we have to build the proper abstractions around the native calls that make it feel idiomatic. For instance, in the case of Haskell, care has to be taken to properly handle side effects, and create a pure, referentially transparent haskell function.
To make it easier, for the direct bindings one can use wrapper generators like swig. These usually consume a header file and produce a language file full of the direct wrappings of the native functions. Then, using these functions one can use the higher-level features of the language and encapsulate it in the way that we feel a library for that purpose in the target language must be like. In the end, we end up with a library that feels natural in the target language and as long as we took the relevant precautions, has all the characteristics of the language that we love.
That is all. So, next time you find yourself thinking “why doesn’t <language here> have bindings for <library here>? <other language here> has them!” don’t ignore the possibility of building the bindings. It is not as hard as it looks (and way more fun than it sounds!), and if you get them completely right and idiomatic you can even help people by publishing them.
Great post, I was expecting something like this a long time ago!
You really impressed me back in September when I saw you creating bidings effortlessly for anything you laid eyes upon, in Lisp. Keep up!
Glad you liked it, thanks for commenting