Next Previous Contents

3.2 Interfacing to Haskell libraries

To demonstrate how HaskellDirect can be used to generate wrappers that lets you package up Haskell code behind a C-callable interface, let's try to expose the following Haskell module to the world:

As I'm sure you'll agree, this is a library that will cause hordes of C developers to come knocking on your door, begging you for a copy :-)

module MathLib where

nfib :: Int -> Int
nfib n | n <= 1    = n
       | otherwise = 1 + nfib (n-1) + nfib (n-2)

fac :: Int -> Int
fac 1    = 1
fac n    = n * fac (n-1)

First step, as always, is to define the functionality you want to export using IDL:

module MathLib {
 [pure]int nfib([in]int n);
 [pure]int fac([in]int n);
};

Use the [pure] attribute here to indicate that we're wrapping functions and not IO actions. To generate proxies from the IDL spec, invoke HaskellDirect as follows:

sof$ ihc -s -fhs-to-c --gen-headers -fuse-ints-everywhere -c MathLib.idl

This generates both a Haskell source file, MathLibProxy.hs, and a C header file, MathLib.h. The generated proxies in MathLibProxy.hs takes care of marshalling values between to and from the functions that MathLib.hs implements, plus all the FFI details of how to make a Haskell function callable from C.

That's it - to try and build a mixed-language application for yourself, see the examples/server directory in the distribution.


Next Previous Contents