Haskell Language Foreign Function Interface

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


  • foreign import ccall unsafe "foo" hFoo :: Int32 -> IO Int32 {- Imports a function named foo in some object file, and defines the symbol hFoo which can be called with Haskell code. -}


While cabal has support for including a C and C++ libraries in a Haskell package, there are a few bugs. First, if you have data (rather than a function) defined in b.o that is used in a.o, and list the C-sources: a.c, b.c, then cabal will be unable to find the data. This is documented in #12152. A workaround when using cabal is to reorder the C-sources list to be C-sources: b.c, a.c. This may not work when using stack, because stack always links the C-sources alphabetically, regardless of the order in which you list them.

Another issues is that you must surround any C++ code in header (.h) files with #ifdef __cplusplus guards. This is because GHC doesn't understand C++ code in header files. You can still write C++ code in header files, but you must surround it with guards.

ccall refers to the calling convention; currently ccall and stdcall (Pascal convention) are supported. The unsafe keyword is optional; this reduces overhead for simple functions but may cause deadlocks if the foreign function blocks indefinitely or has insufficient permission to execute1.

Got any Haskell Language Question?