Subscribe to
Posts
Comments

We received a number of great submissions within hours of posting our request for suggestions for a library to develop bindings for in the FFI chapter. Thanks to everyone who contributed.

After looking over the alternatives, we’ve decided to use PCRE as the example. Even though there already exist useful bindings to PCRE, it’s still a good choice for teaching about the FFI, for a number of solid reasons.

  • It’s small: its header file is only 300 lines long, and contains plenty of comments. We can thus cover its API almost completely, giving a thorough picture of how to build useful bindings.
  • There’s no doubt that it’s both useful and portable.
  • Its C API requires that users allocate and free objects manually. We can thus demonstrate how to eliminate the need to manually track objects in the Haskell bindings, through the use of finalisers.
  • We can start off simply, with bindings to Haskell’s String type, and then show how to improve performance by using ByteStrings.
  • It provides a callback facility, so we demonstrate inversion of control: not only how to call C from Haskell, but how to call Haskell code from C.

For teaching purposes, that’s a pretty compelling set of features. Thanks once more to those who submitted their ideas!

5 Responses to “And the winner is … PCRE!”

  1. [...] 2008-05-12: We’ve decided to go with PCRE. Thanks for all of your [...]

  2. on 12 May 2008 at 23:12 UTCGour

    Hi!

    Will you show how to write bindings ‘by hand’ or do you plan to cover binding-generators like c2hs as well?

    Sincerely,
    Gour

  3. on 12 May 2008 at 23:12 UTCBryan O'Sullivan

    We might cover hsc2hs, but not c2hs.

  4. on 13 May 2008 at 01:48 UTCStuart Dootson

    Bryan – I presume this will all use Haskell for the ‘main’, and won’t describe calling Haskell code from a program using (say) a C ‘main’?

    I’ve found that the bits of FFI I’ve done have been pretty easy to accomplish, but calling Haskell from a C ‘main’ was rather more painful, until I found the right combination of Haskell syntax, GHC flags and calls from C to make it all work.

  5. on 15 May 2008 at 06:51 UTCJim Crayne

    These Would be Great Practical Topics
    =======================
    Calling from a C `main’ is very useful for embedding Haskell in already existing projects. The GHC manual covers how to do this with a library, but how about if you just want to mix haskell modules in?

    Doing your own linking rather than having ghc do it. You might want libgmp linked dynamically while everything else is linked statically.. Or some other special scenario.

    Setting up common IDEs like Visual Studio & XCode to compile and link haskell files as readily as c ones.