Mar 20 2008

Initial foray into Haskell FFI

Published by Dougal at 5:08 pm under Programming

Been trying — and mostly failing — to engage with Haskell’s foreign function interface (FFI). I have just managed to get something together although bits of it are closer to cargo cult programming at the moment. Write these keywords, intone these phrases, bam it works.

Lost at C

For this exercise I wanted to write a ‘library’ in C then call it from within the Haskell code. My magic C library has two parts, foo.c and foo.h. The first part squares the supplied integer! Amazing!

#include "foo.h"
 
int square(int n)
{
    return n * n;
}

The other part is the header file for this:

int square(int n);

I bet you would all have struggled to come up with something so hardcore…

Deep Voodoo

The Haskell to link to this great library is:

module Main where
 
import System.Environment
 
main = do [n] <- getArgs
          print $ sqr $ read n
 
foreign import ccall "foo.h square" sqr :: Int -> Int

And I have to admit that the last line doesn’t really mean much to me. I know what all the bits do, but I wouldn’t know how to adapt that to more interesting or varied callouts.

But one step at a time is the way to go.

Compilation and Linking

The first step is to create the library we want to call out to, then build the Haskell around it.

$ ghc -c foo.c
$ ghc --make -fffi Foo.hs foo.o -o foo

So you need to create foo.o and then pass it and the Haskell source to the compiler with the -fffi argument. Then we try it out:

$ ./foo 3
9

Not bad. (Though not actually what one might call “good” either. Merely satisfactory.) At some later point I will attempt side-effectful functions and maybe even some data structures.

Trackback URI | Comments RSS

Leave a Reply