FFI

Manuel M. T. Chakravarty chak@cse.unsw.edu.au
Mon, 14 Jan 2002 16:45:12 +1100


Dylan Thurston <dpt@petunia.bostoncoop.net> wrote,

> On Sat, Jan 12, 2002 at 01:24:54PM +1100, Manuel M. T. Chakravarty wrote:
> > I think, there are five options:
> > 
> > * H/Direct (you mentioned that already)
> > * GreenCard (ditto)
> > * C->Haskell
> >   http://www.cse.unsw.edu.au/~chak/haskell/c2hs/
> > * hsc2hs (comes with GHC)
> > * Plain FFI
> 
> And what are the pros and cons of each?  Presumably you recommend
> C->Haskell, since you wrote it; what makes it better?

Since your are asking, here my shamelessly biased opinion ;-)

I don't think that it makes much sense coding on the plain
FFI unless there are reasons for avoiding an extra tool or
the binding is very small.  Moreover, GreenCard (with all
due respect) is a bit of a legacy.  The other three tools
clearly benefited from the GreenCard experience, but after
all they were developed, because the authors thought that
they can improve on GreenCard.  This leaves us with
H/Direct, C->Haskell, and hsc2hs.

I chose the order of listing these three tools on purpose.
It is not only the historical order, but enumerates them in
order of decreasing complexity.  H/Direct is clearly the
most powerful of the three.  It is an IDL compiler with the
ability to process a combination of C header files and
matching annotation files as a form of poor man's IDL,
whereas C->Haskell and hsc2hs only have one goal: Simplify
the development of Haskell bindings to C libraries.

I believe in the design philosophy of having a set of small
tools that do just one job, but do it well.  So, I prefer
a specialised tool like C->Haskell and besides, when I
initially developed C->Haskell, H/Direct couldn't handle C
headers yet.  As for a feature comparison, this is what
comes to my mind:

H/Direct pros:
- It can automatically marshal structures.  In C->Haskell,
  you have to do some of this manually.  Automating the
  process is on the todo list.

C->Haskell pros:
- Given a header file, you write on file which contains the
  Haskell API and binding hooks that link the Haskell
  entities to C entities.  With H/Direct, you need the
  annotation file plus usually a Haskell module that
  redresses the automatically generated interface to what
  you want to present to the user.
- Marshalling is expressed using a marshalling library in
  plain Haskell, which means it is easy to write special
  code to handle weird cases.

Regarding hsc2hs, it's idea was to be even simpler than
C->Haskell.  In particular, it is independent of the used C
compiler, whereas C->Haskell has to imitate part of what a C
compiler does.  However, this comes at the expense of IMHO
rather messy quoting requirements.  Moreover, there is the
potential in C->Haskell to provide quite a bit more
automation than it implements at the moment.

Cheers,
Manuel