[Haskell-cafe] ANNOUNCE: libffi 0.1 released

Remi Turk rturk at science.uva.nl
Tue Mar 17 10:17:29 EDT 2009

I am happy to announce libffi 0.1, binding to the C library
libffi, allowing C functions to be called whose types are not
known before run-time.


Sometimes you can't use the haskell foreign function interface
because you parse the type of the function from somewhere else,
i.e. you're writing an interpreter for a language that has an FFI


The main function it exports is:

  callFFI :: FunPtr a -> RetType b -> [Arg] -> IO b

And because code is worth a thousand words, here a small program
that uses C to write a 1Gb buffer of random garbage to a file:

> import System.Posix.DynamicLinker
> import Foreign.LibFFI
> main = do
>     malloc <- dlsym Default "malloc"
>     creat  <- dlsym Default "creat"
>     write  <- dlsym Default "write"
>     let sz = 2 ^ 30
>     buf <- callFFI malloc (retPtr retVoid) [argCSize sz]
>     fd  <- callFFI creat  retCInt          [argString "/tmp/test", argCUInt 0o644]
>     n   <- callFFI write  retCSize         [argCInt fd, argPtr buf, argCSize sz]
>     putStrLn $ show n ++ " bytes written"

It should work on any 32/64bits machine on which libffi works,
but has been primarily tested on linux x86_64.
The current libffi is not exception-safe (exception = memory leak)
and callFFI has quite some overhead that would be unnecessary
with another api. 
It is, however, very easy to use :)

More interesting examples are included in examples/ in the

Hackage: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/libffi
Module docs: http://www.science.uva.nl/~rturk/doc/libffi-0.1

Cheers, Remi

More information about the Haskell-Cafe mailing list