Chapter 8.  Foreign function interface (FFI)

Table of Contents

8.1. GHC extensions to the FFI Addendum
8.1.1. Unboxed types
8.1.2. Newtype wrapping of the IO monad
8.2. Using the FFI with GHC
8.2.1. Using foreign export and foreign import ccall "wrapper" with GHC
8.2.1.1. Using your own main()
8.2.1.2. Using foreign import ccall "wrapper" with GHC
8.2.2. Using function headers
8.2.2.1. Finding Header files
8.2.3. Memory Allocation

GHC (mostly) conforms to the Haskell 98 Foreign Function Interface Addendum 1.0, whose definition is available from http://haskell.org/.

To enable FFI support in GHC, give the -fffiflag, or the -fglasgow-exts flag which implies -fffi .

The FFI support in GHC diverges from the Addendum in the following ways:

The FFI libraries are documented in the accompanying library documentation; see for example the Foreign module.

8.1. GHC extensions to the FFI Addendum

The FFI features that are described in this section are specific to GHC. Avoid them where possible to not compromise the portability of the resulting code.

8.1.1. Unboxed types

The following unboxed types may be used as basic foreign types (see FFI Addendum, Section 3.2): Int#, Word#, Char#, Float#, Double#, Addr#, StablePtr# a, MutableByteArray#, ForeignObj#, and ByteArray#.

8.1.2. Newtype wrapping of the IO monad

The FFI spec requires the IO monad to appear in various places, but it can sometimes be convenient to wrap the IO monad in a newtype, thus:

  newtype MyIO a = MIO (IO a)

(A reason for doing so might be to prevent the programmer from calling arbitrary IO procedures in some part of the program.)

The Haskell FFI already specifies that arguments and results of foreign imports and exports will be automatically unwrapped if they are newtypes (Section 3.2 of the FFI addendum). GHC extends the FFI by automatically unnwrapping any newtypes that wrap the IO monad itself. More precisely, wherever the FFI specification requires an IO type, GHC will accept any newtype-wrapping of an IO type. For example, these declarations are OK:

   foreign import foo :: Int -> MyIO Int
   foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int