Personal tools

Calling Haskell from C

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
 
Line 59: Line 59:
 
And that's it.
 
And that's it.
   
[[Category:Tutorial]]
+
[[Category:Tutorials]]

Revision as of 03:33, 24 June 2008

It is not uncommon to want to call a Haskell function from C code. Here's how to do that.

We define the fibonacci function in Haskell:

    {-# LANGUAGE ForeignFunctionInterface #-}
 
    module Safe where
 
    import Foreign.C.Types
 
    fibonacci :: Int -> Int
    fibonacci n = fibs !! n
        where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
 
    fibonacci_hs :: CInt -> CInt
    fibonacci_hs = fromIntegral . fibonacci . fromIntegral
 
    foreign export ccall fibonacci_hs :: CInt -> CInt

Note the foreign export. When GHC sees this, it will generate stubs for C, to help it work out the Haskell types.

And call it from C:

    #include "A_stub.h"
    #include <stdio.h>
 
    int main(int argc, char *argv[]) {
       int i;
       hs_init(&argc, &argv);
 
       i = fibonacci_hs(42);
       printf("Fibonacci: %d\n", i);
 
       hs_exit();
       return 0;
    }

Now, first compile the Haskell file:

   $ ghc -c -O A.hs

Which creates some *.c and *.h headers, which you import into your C program. Now compile your C code with ghc (!), passing the Haskell objects on the command line:

   $ ghc -optc-O test.c A.o A_stub.o -o test

How run your C code:

   $ ./test 
   Fibonacci: 267914296

And that's it.