Being called from C
foreign export ccall
The other direction is a Haskell function with a C name, written with foreign export. The Haskell function is ordinary; the string is the symbol a C program will call:
module Adder (hsAdd) where import Foreign.C.Types (CInt (..)) foreign export ccall "hs_add" hsAdd :: CInt -> CInt -> CInt hsAdd :: CInt -> CInt -> CInt hsAdd a b = a + b
The compiler generates a C function hs_add with the given signature and a header, and the module has no main: it is a library, not a program. The C name is written out on purpose so the C side does not have to know the Haskell name mangling, and hlint asks for camel case in the Haskell name while the symbol keeps the underscore.
The C driver
A C program that calls the exported function has to start the Haskell runtime first and stop it at the end. hs_init takes the address of argc and argv, or two nulls:
#include <stdio.h> #include <HsFFI.h> extern HsInt32 hs_add(HsInt32 a, HsInt32 b); int main(void) { hs_init(NULL, NULL); printf("%d\n", (int)hs_add(20, 22)); hs_exit(); return 0; }
HsFFI.h defines HsInt32 and the other C-side types of the FFI, and GHC installs it with the runtime. The driver treats the Haskell function like any other C function: it passes two integers and prints the result.
Building the driver
The simplest build links the C driver and the Haskell module into one static binary. -no-hs-main tells GHC that the main comes from C and not from a Haskell module:
ghc -Wall -no-hs-main driver.c Adder.hs -o driver
./driver
[1 of 2] Compiling Adder ( Adder.hs, Adder.o )
[2 of 2] Linking driver
42
One command compiles the Haskell module, compiles the C file with the include path of the runtime and links both with the RTS, which is why the C driver does not have to name the runtime library itself. The result is a single executable: no .so, no loader path, and no LD_LIBRARY_PATH to set.
The shared library: the plain command fails, -dynamic works
A shared library is the form a Python process or a long-running server needs. The command is ghc -shared -fPIC, and on this image it fails at the linker, because the GHC libraries are static archives that were not compiled with position-independent code:
ghc -shared -fPIC -o libadder.so Adder.hs
[1 of 2] Compiling Adder ( Adder.hs, Adder.o ) [Flags changed]
[2 of 2] Linking libadder.so
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld: /usr/lib/ghc-9.10.3/lib/../lib/x86_64-linux-ghc-9.10.3-inplace/ghc-internal-9.1003.0-inplace/libHSghc-internal-9.1003.0-inplace.a(Types.o): relocation R_X86_64_32S against undefined symbol `stg_upd_frame_info' can not be used when making a shared object; recompile with -fPIC
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld: failed to set dynamic section sizes: bad value
collect2: error: ld returned 1 exit status
ghc-9.10.3: `cc' failed in phase `Linker'. (Exit code: 1)
HasCallStack backtrace:
collectBacktraces, called at libraries/ghc-internal/src/GHC/Internal/Exception.hs:169:13 in ghc-internal:GHC.Internal.Exception
toExceptionWithBacktrace, called at libraries/ghc-internal/src/GHC/Internal/IO.hs:260:11 in ghc-internal:GHC.Internal.IO
throwIO, called at libraries/exceptions/src/Control/Monad/Catch.hs:308:12 in exceptions-0.10.9-inplace:Control.Monad.Catch
throwM, called at libraries/exceptions/src/Control/Monad/Catch.hs:797:84 in exceptions-0.10.9-inplace:Control.Monad.Catch
onException, called at compiler/GHC/Driver/Make.hs:2983:23 in ghc-9.10.3-inplace:GHC.Driver.Make
The message is precise: an object inside the runtime archive has a relocation that cannot go into a shared object, and GHC 9.10 follows the error with a call-stack backtrace of its own driver. The same GHC installation also ships the shared versions of those libraries, and -dynamic is what tells GHC to link them instead of the archives. The runtime is one of them and is not added by default, so it is named on the command line:
ghc -O1 -shared -dynamic -fPIC -o libadder.so Adder.hs -lHSrts-1.0.2-ghc9.10.3
[1 of 2] Compiling Adder ( Adder.hs, Adder.o )
[2 of 2] Linking libadder.so
The file is built and exports the C symbol. The driver links against it with -ladder, and at run time the loader has to be told where the library is, which is the difference from the static build above:
ghc -Wall -no-hs-main -dynamic driver.c -o driver_shared -L. -ladder
LD_LIBRARY_PATH=. ./driver_shared
42
The link step prints nothing when it succeeds. The binary names libadder.so and the shared runtime as dependencies, so the folder with the library is in LD_LIBRARY_PATH for the run; the static driver needs neither the file nor the variable.
Handles and the stable pointer question
The C side of an exported function can hold a pointer to a Haskell value only if the value is made stable, because the garbage collector moves values and the C pointer would go stale. The tools are:
- newStablePtr and freeStablePtr, which pin a value and give a StablePtr that C can keep.
- foreign import ccall "wrapper", which turns a Haskell function into a C function pointer for a callback.
- The rule of thumb: pass numbers by value, copy strings at the boundary, and keep a stable pointer only for a value that must outlive the call.
The next lesson calls this same libadder.so from Python with ctypes and measures both routes into Haskell: the library call and a process per call.
Exercises
- Add an exported hs_mul and call it from the driver.
- Pass the program arguments to hs_init and print them from Haskell.
- Export a function that returns a HsBool and use it in an if on the C side.
- Explain why hs_exit is needed and what happens without it.
- Read the linker error above and say which object and which relocation it names.
- Explain when a StablePtr is necessary.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
foreign export ccall "hs_add" hsAdddo?Answer
Generates a C function hs_add that calls the Haskell function
The export direction makes a C symbol for a Haskell definition.
-
What must a C driver call before and after the Haskell functions?
Answer
hs_initandhs_exitThe runtime has to start and stop around the calls.
-
What does
-no-hs-maintell GHC?Answer
The main function comes from C, not from a Haskell module
The flag lets the C main be the entry point while the RTS is still linked.
-
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 (-42))Answer
42
abs returns the positive value and print shows it.
-
Why does
ghc -sharedfail on this image?Answer
The runtime archives were not compiled with -fPIC
The linker reports a relocation that cannot be used in a shared object; -dynamic links the shared versions of the same libraries instead.
-
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 0)Answer
0
abs of zero is zero and print shows it as a number.
-
Which C header defines the FFI types such as HsInt32?
Answer
HsFFI.hHsFFI.h ships with GHC and is found through the include path of the runtime.
-
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 (-8)) :: Int)Answer
8
The CInt 8 is converted to Int and print shows 8.
-
When is a stable pointer needed?
Answer
When C must keep a pointer to a Haskell value across calls
The GC may move values, and a stable pointer keeps the address valid.
-
What is the difference between
foreign importandforeign export?Answer
Import calls C from Haskell, export makes a C symbol for a Haskell function
The two directions of the FFI are import and export.
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