A Brief Introduction to Haskell’s FFI

Haskell, like many other languages, has the ability to call native code. It also has an interface for native code to call Haskell, but we aren’t going to explore that in this chapter. We are interested in the ability for Haskell to call our native Caesar cipher implementation.

Haskell’s Foreign Function Interface (FFI) can be invoked using the following construct:

 caesar.hs
 
 foreign import ccall "caesar.h caesar" c_caesar
  :: CInt -> CString -> CString

It starts with foreign import ccall, which signals our call. It’s followed by the location where the function is defined and the name of the function we wish to call. Next we provide a name that we can use for this function inside our Haskell code. ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.