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:
- CInt is a 32-bit signed integer on this platform; Int is a machine word and is 64 bits here. The fromIntegral in the wrapper is the conversion, and a value that does not fit is truncated without a warning.
- CString is a pointer to bytes ending in zero; a Haskell String is a list of characters. The conversion is an allocation and the memory has to be freed with withCString, which is the next lesson but two.
- A Ptr a is an address the Haskell side does not interpret; passing one to C is fine and dereferencing it needs Storable or peek.
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
- Call getpid from libc and print the process id.
- Add a C function max2 and call it from Haskell with two values.
- Write a C function that squares a double and call it with CDouble.
- Explain what happens when a Haskell Int larger than 2^31 is passed as a CInt.
- Build the C file into an object with gcc -c and link it with ghc, and compare the commands.
- 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.
-
What does
foreign import ccall "abs" c_abs :: CInt -> CIntmean?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.
-
Why does the FFI use
CIntand notInt?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.
-
What does the build
ghc Main.hs Silly.hs add.c -o appdo?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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
Which module holds the C types?
Answer
Foreign.C.TypesCInt, CDouble, CString and the rest are in Foreign.C.Types and the other Foreign modules.
-
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