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 this image cannot build

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)

The message is precise: an object inside the runtime archive has a relocation that cannot go into a shared object, and the fix is a GHC built with -fPIC libraries (the ghc packages of a distribution that ships dynamic libraries). This image has the static ones, so the shared-library part of the next lesson is written as a source and marked as not run here; the static driver above is the proof that the export itself works.

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:

The next lesson takes the shared library as a source, calls it from Python with ctypes, and measures the call it can make here: a subprocess to the executable, which needs no shared library at all.

Exercises

  1. Add an exported hs_mul and call it from the driver.
  2. Pass the program arguments to hs_init and print them from Haskell.
  3. Export a function that returns a HsBool and use it in an if on the C side.
  4. Explain why hs_exit is needed and what happens without it.
  5. Read the linker error above and say which object and which relocation it names.
  6. 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.

  1. What does foreign export ccall "hs_add" hsAdd do?

    Answer

    Generates a C function hs_add that calls the Haskell function

    The export direction makes a C symbol for a Haskell definition.

  2. What must a C driver call before and after the Haskell functions?

    Answer

    hs_init and hs_exit

    The runtime has to start and stop around the calls.

  3. What does -no-hs-main tell 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.

  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 (-42))

    Answer

    42

    abs returns the positive value and print shows it.

  5. Why does ghc -shared fail 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.

  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 (c_abs 0)

    Answer

    0

    abs of zero is zero and print shows it as a number.

  7. Which C header defines the FFI types such as HsInt32?

    Answer

    HsFFI.h

    HsFFI.h ships with GHC and is found through the include path of the runtime.

  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 (fromIntegral (c_abs (-8)) :: Int)

    Answer

    8

    The CInt 8 is converted to Int and print shows 8.

  9. 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.

  10. What is the difference between foreign import and foreign 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

Banner image