From Haskell to C and C to Haskell
A classic usage of the FFI is calling C functions from Haskell. So let's start with that. Consider that you wrote a function in C, for instance the recursive nth Fibonacci number like the fib.c
file here:
/* file: fib.c */ int fib_c(int num) { if (num <= 2) { return 1; } else { return(fib_c(num - 1) + fib_c(num - 2)); } }
Although naive, this implementation is still faster than the Haskell equivalent.
Now, to call this fast naive fib_c
function from Haskell, at its simplest we could just add the following line to a Haskell source file and then we would have a fib_c :: Int → Int
Haskell function:
-- file: ffi-fib.hs foreign import ccall fib_c :: Int -> Int main = print $ fib_c 20
The only FFI-specific thing here is foreign import
. Note that, with some earlier versions of GHC, it was necessary to explicitly enable the FFI with -XForeignFunctionInterface
.
To compile this program, we should give both the Haskell and C...