Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active January 12, 2022 22:23
Show Gist options
  • Save CMCDragonkai/5339b6a95433acd7d89a to your computer and use it in GitHub Desktop.
Save CMCDragonkai/5339b6a95433acd7d89a to your computer and use it in GitHub Desktop.
Haskell: Interoperability with other Languages

Haskell Interoperability

There's a number of possible ways to communicate between programms in different languages. There's of course IPC and RPC, but what about actual linking with binary code? Such a feature would allow using C as the portable interface between languages, call into the kernel directly, and also allow Haskell to use existing high quality scientific and numerical libraries. All of this without having the overhead of developing and maintaining a second running process.

Well Haskell has great FFI support! The below resources demonstrate linking Haskell libraries (dynamically or statically) into other languages including C, C++ and any other language that supports foreign C imports. It also demonstrates how Haskell can use C exposed libraries too (through object or shared object files).

Here are some examples that uses Template Haskell to embed other languages inside Haskell inline as compile-time macros. This is language composition awesome!

Note that of course some languages may only consume C exposed libraries, but may not expose their own code through a C header. For these languages you can call into Haskell, but Haskell cannot call into these languages. This is true for the majority of interpreted/non-compiled languages. Unless of course those languaages are implemented in C, and its interpreter exposes C functions. Like for example CPython.

GC Issues

When calling from non-GC language to a GC language like Haskell. Be aware of controlling how to garbage collect memory in Haskell. See: http://stackoverflow.com/q/28465113/582917

Shared Libraries

By the way dynamic linking means that there's only one instance of that library being loaded into memory. So if multiple processes use the same shared library, you get disk space savings and memory usage savings! But beware of concurrency issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment