Note that the FFI document recommends putting the header in the double quotes, like

foreign import ccall "math.h sin" c_sin :: CDouble -> CDouble

GHC since 6.10.x ignores both the INCLUDE pragma (equivalently command line -#include) and the header in the double quotes. GHC 6.8.x and before prefers the INCLUDE pragma (equivalently command line -#include) and in Cabal package descriptions. Other compilers probably prefer the header in the double quotes (if they compile via C) or ignore (if they do not compile via C)—check their documentations.

Notice that C types are not the same as Haskell types, and you have to import them from Foreign.C. Notice also that, as usual in Haskell, you have to explicitly convert to and from Haskell types. Using c_<name_of_c_function> for the raw C function is just my convention.

The Haskell report only guarantees that Int has 30 bits of signed precision, so converting CInt to Int is not safe! On the other hand, many classes have instances for Int and Integer but not CInt, so it's generally more convenient to convert from the C types. To convert, I suppose you could either write a checkedFromIntegral function if you're sure it's small or just use Integer.

For details on impure functions, pointers to objects, etc., see the cookbook.

3 Marshalling and unmarshalling arguments

See the cookbook. It's nicer to do the marshalling and unmarshalling in Haskell, but it's still low-level repetitive stuff. The functions are all available below Foreign, which supports memory allocation and pointers (and hence C arrays and "out" parameters). One thing it doesn't support is structs.

Tools like c2hs were created to help with this (as well as the low-level boilerplate thing).

[ TODO: more detail here? examples in c2hs? ]

4 Compiling FFI-using modules

4.1 GHC

Here's a makefile fragment to compile an FfiExample module that uses C functions from c_functions.c, which uses library functions from libcfuncs:

Notice the use of _dummy_target and --make. The idea is that you get make to compile what is necessary for C, and then always run ghc with --make, at which point it will figure out what is necessary to compile for Haskell.

Actually, this is broken, because ghc --make will not notice if a .o file has changed!

[ this is just my hack, anyone have a better way to do this? ]

4.2 Other compilers

Fill me in!

5 Complete example with GHC

GHC's libs don't (apparently?) support generic termios stuff. I could implement the whole tcgetattr / tcsetattr thing, but let's just turn ICANON on and off, so IO.getChar doesn't wait for a newline: