Haskell Language Foreign Function Interface Calling C from Haskell


Example

For performance reasons, or due to the existence of mature C libraries, you may want to call C code from a Haskell program. Here is a simple example of how you can pass data to a C library and get an answer back.

foo.c:

#include <inttypes.h>

int32_t foo(int32_t a) {
  return a+1;
}

Foo.hs:

import Data.Int

main :: IO ()
main = print =<< hFoo 41

foreign import ccall unsafe "foo" hFoo :: Int32 -> IO Int32

The unsafe keyword generates a more efficient call than 'safe', but requires that the C code never makes a callback to the Haskell system. Since foo is completely in C and will never call Haskell, we can use unsafe.

We also need to instruct cabal to compile and link in C source.

foo.cabal:

name:                foo
version:             0.0.0.1
build-type:          Simple
extra-source-files:  *.c
cabal-version:       >= 1.10

executable foo
  default-language: Haskell2010
  main-is:       Foo.hs
  C-sources:     foo.c
  build-depends: base

Then you can run:

> cabal configure
> cabal build foo
> ./dist/build/foo/foo
42