Calling C from Haskell

foreign import ccall

The foreign function interface declares a C function to Haskell with a signature. The declaration has no body: the name in the string is the symbol the linker will look for, and the Haskell name is the one the program uses:

foreign import ccall "abs" c_abs :: CInt -> CInt

ccall is the calling convention, which is the one of every ordinary C function. The types have to be the C types: CInt, CDouble, CString and the rest of Foreign.C, because a Haskell Int and a C int are not the same width on every platform. The conversion is explicit, with fromIntegral or one of the helpers.

A function from libc

A function that is already in the C library the program links against needs no extra file, and it is the smallest FFI program: no build flag beyond the usual one.

module Main (main) where import Foreign.C.Types (CInt (..)) foreign import ccall "abs" c_abs :: CInt -> CInt main :: IO () main = print (c_abs (-42))

ghc -Wall -O1 -o abs abs.hs
./abs

42

The call is a real call into libc, and the result is a CInt that print shows as a number. The build line is the one of every other lesson, because the symbol comes from the C library that GHC links anyway. That is the way to reach strlen, getpid or a mathematical function of the platform.

A C file of your own

A function you wrote lives in a C file, and the file joins the ghc command. The C side is one function with the types of the header:

#include <stdint.h> int32_t add(int32_t a, int32_t b) { return a + b; }

The Haskell side declares the symbol and wraps it in an ordinary function with ordinary Haskell types. The wrapper is the boundary, and it is the only place where the conversion happens:

module Silly (add) where import Foreign.C.Types (CInt (..)) foreign import ccall "add" c_add :: CInt -> CInt -> CInt add :: Int -> Int -> Int add a b = fromIntegral (c_add (fromIntegral a) (fromIntegral b))

The program imports the wrapper and does not know that C is involved. The build names the C file and the compiler passes it to the C compiler and links the object:

module Main (main) where import Silly (add) main :: IO () main = print (add 20 22)

ghc -Wall -O1 Main.hs Silly.hs add.c -o app
./app

[1 of 3] Compiling Silly ( Silly.hs, Silly.o )
[2 of 3] Compiling Main ( Main.hs, Main.o )
[3 of 3] Linking app
42

Three files, one command, one binary. GHC compiles the two Haskell modules and then calls the C compiler for add.c, and the linker joins the objects. A missing C file is a link error about the symbol add and not a compile error in the Haskell code, which is the first thing to check when an FFI program fails to link.

The marshalling between types

The types on the two sides are not the same, and the wrapper is where they meet:

An FFI call is a place where a Haskell program can crash the runtime, because C does not know about laziness or garbage collection. The rules are to keep the C side short, to pass only types the C header defines, and to copy data at the boundary instead of holding a Haskell reference. The next lesson turns the direction around and lets C call Haskell.

Exercises

  1. Call getpid from libc and print the process id.
  2. Add a C function max2 and call it from Haskell with two values.
  3. Write a C function that squares a double and call it with CDouble.
  4. Explain what happens when a Haskell Int larger than 2^31 is passed as a CInt.
  5. Build the C file into an object with gcc -c and link it with ghc, and compare the commands.
  6. Explain why the foreign import has no body and where the body is.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does foreign import ccall "abs" c_abs :: CInt -> CInt mean?

    Answer

    Call the C symbol abs as c_abs with the C integer types

    The string is the C symbol, the convention is ccall and the types are the C ones.

  2. Why does the FFI use CInt and not Int?

    Answer

    The C type has a fixed width; Int is the machine word

    The widths differ between the two languages, so the boundary uses the C types.

  3. What does the build ghc Main.hs Silly.hs add.c -o app do?

    Answer

    Compiles the modules, compiles the C file and links one binary

    GHC drives the C compiler for the .c file and links the objects.

  4. What does this program print? module Main (main) where import Foreign.C.Types (CInt (..)) foreign import ccall "abs" c_abs :: CInt -> CInt main :: IO () main = print (c_abs (-7))

    Answer

    7

    abs returns the absolute value, which print shows as a number.

  5. Where does the body of a foreign import come from?

    Answer

    From the C object or library named by the symbol at link time

    The declaration is resolved by the linker against the C symbol.

  6. What does this program print? module Main (main) where import Foreign.C.Types (CInt (..)) foreign import ccall "abs" c_abs :: CInt -> CInt main :: IO () main = print (fromIntegral (c_abs (-3)) + 1 :: Int)

    Answer

    4

    abs gives 3, fromIntegral makes it an Int and the expression adds 1.

  7. What is the risk of an FFI call?

    Answer

    C does not know about laziness or GC, so a bad call can crash the runtime

    The boundary is the unsafe part and needs the C types and rules.

  8. What does this program print? module Main (main) where import Foreign.C.Types (CInt (..)) foreign import ccall "abs" c_abs :: CInt -> CInt main :: IO () main = print (c_abs 5 + c_abs (-5))

    Answer

    10

    Both calls return 5 and CInt has a Num instance, so the sum is 10.

  9. Which module holds the C types?

    Answer

    Foreign.C.Types

    CInt, CDouble, CString and the rest are in Foreign.C.Types and the other Foreign modules.

  10. What is a CString?

    Answer

    A pointer to zero-terminated bytes

    The C string is a pointer, and converting it allocates and frees.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image