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.1.3. Primitive imports
8.2. Using the FFI with GHC
8.2.1. Using foreign export and foreign import ccall "wrapper" with GHC Using your own main() Making a Haskell library that can be called from foreign code
8.2.2. Using header files
8.2.3. Memory Allocation
8.2.4. Multi-threading and the FFI Foreign imports and multi-threading The relationship between Haskell threads and OS threads Foreign exports and multi-threading On the use of hs_exit()
8.2.5. Floating point and the FFI

GHC (mostly) conforms to the Haskell 98 Foreign Function Interface Addendum 1.0, whose definition is available from

To enable FFI support in GHC, give the -XForeignFunctionInterface flag.

GHC implements a number of GHC-specific extensions to the FFI Addendum. These extensions are described in Section 8.1, “GHC extensions to the FFI Addendum”, but please note that programs using these features are not portable. Hence, these features should be avoided where possible.

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. Your code will not be portable to other compilers if you use them.

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 unwrapping 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

8.1.3. Primitive imports

GHC extends the FFI with an additional calling convention prim, e.g.:

   foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)

This is used to import functions written in Cmm code that follow an internal GHC calling convention. This feature is not intended for use outside of the core libraries that come with GHC. For more details see the GHC developer wiki.