Calling Haskell from Python

Two ways into Haskell from Python

A Python program that wants a Haskell function has two routes:

Both routes run here and the page measures both. The library is the one the previous lesson built with -dynamic, and the executable is the small program further down. A call through the library costs a few microseconds and a call through a process a few milliseconds.

The ctypes client

The Haskell side is the module of the previous lesson: one exported function with a C name and no main.

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 build is the -dynamic one, because the plain ghc -shared -fPIC fails on the static archives:

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 client loads the library, starts the runtime once, declares the two argument and result types, and calls the exported symbol. The declaration is not optional: without it ctypes passes Python ints as C int and the call may still work, or not, depending on the platform. The path is built from the file the script lives in, so the client runs from any directory and never names a scratch folder:

import ctypes import os LIB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "libadder.so") lib = ctypes.CDLL(LIB) lib.hs_init.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_char_p)] lib.hs_init(None, None) add = lib.hs_add add.argtypes = [ctypes.c_int32, ctypes.c_int32] add.restype = ctypes.c_int32 if __name__ == "__main__": print(add(20, 22)) lib.hs_exit()

python3 call.py

42

The call is a direct function call with no process involved. The hs_init line is the whole difference between a working library and a dead process: the same call without it stops at the first instruction that needs the runtime:

python3 -c 'import ctypes; print(ctypes.CDLL("./libadder.so").hs_add(20, 22))'

newBoundTask: RTS is not initialised; call hs_init() first

The message comes from the runtime, not from Python, and the exit status is 1. A library of this shape has to document that its caller initialises it, and a Python package that wraps one does it at import.

The ctypes call, measured

One function measures and one prints. Each round calls add a fixed number of times and divides the elapsed wall clock by that number, so every sample is a per-call time in microseconds. Two sizes, fifty calls and five thousand, five rounds each: the small one is what a request handler does, and the long one shows what the call costs when one reading of the clock covers many of them.

"""Per-call cost of the ctypes call, at two sizes.""" import statistics import time from call import add ARGS = (20, 22) def measure(repeats: int, rounds: int = 5) -> list[float]: """Per-call microseconds for each round of `repeats` calls.""" samples = [] for _ in range(rounds): start = time.perf_counter() for _ in range(repeats): add(*ARGS) samples.append((time.perf_counter() - start) / repeats * 1_000_000) return samples def report(name: str, samples: list[float]) -> None: values = " ".join(f"{sample:8.2f}" for sample in samples) print(f"{name:22s}{values} min {min(samples):7.2f} median {statistics.median(samples):7.2f}") if __name__ == "__main__": report("ctypes, 50 calls", measure(50)) report("ctypes, 5000 calls", measure(5000))

python3 timing.py

ctypes, 50 calls 3.68 2.89 2.76 2.82 2.86 min 2.76 median 2.86
ctypes, 5000 calls 2.38 1.80 1.81 1.79 1.74 min 1.74 median 1.80

Under three microseconds per call at both sizes: the cost does not grow with the length of the batch, and the longer round has the smaller minimum because the clock is read once for five thousand calls instead of once for fifty. The machine and the settings behind the numbers:

The subprocess route, measured

The out-of-process route needs no library. The program adds the two numbers it is given and prints the sum:

module Main (main) where import System.Environment (getArgs) import Text.Read (readMaybe) main :: IO () main = do args <- getArgs case map readMaybe args :: [Maybe Int] of [Just a, Just b] -> print (a + b) _ -> putStrLn "usage: adder A B"

The Python side runs it fifty times and divides the elapsed time by the number of calls. check=True makes a non-zero status an exception, so a broken call is not silently counted:

import subprocess import time runs = 50 start = time.perf_counter() for _ in range(runs): subprocess.run(["./adder", "20", "22"], capture_output=True, check=True) elapsed = time.perf_counter() - start print(f"{runs} calls in {elapsed:.3f} s") print(f"{elapsed / runs * 1000:.2f} ms per call")

ghc -Wall -O1 -o adder adder.hs
./adder 20 22
python3 call_subprocess.py

[1 of 2] Compiling Main ( adder.hs, adder.o )
[2 of 2] Linking adder
42
50 calls in 0.132 s
2.64 ms per call

Two and a half milliseconds per call is the cost of starting a process and nothing else: the addition itself is nanoseconds. Against the 1.80 microseconds of the library call the process route is about 1,500 times more expensive per call. For fifty calls the subprocess route is fine; for fifty thousand, the in-process call is the only one that makes sense, which is why the shared library exists. A middle way is a long-running Haskell process that reads requests from stdin, which the lesson on stdin and stdout described and a capstone later uses.

Bytes, strings and lifetime

Three rules cover the boundary, and they apply to every FFI language pair:

The next lesson stays on the Haskell side and parses text with the parsec library, which is the tool a program that reads a line protocol uses before any of this marshalling.

Exercises

  1. Change the Haskell program to read two numbers from one line of stdin and call it once for ten pairs.
  2. Measure the same fifty calls with ./adder started once and fed all the pairs, and compare.
  3. Write the ctypes declaration for a function that takes a c_char_p and returns an int32.
  4. Explain why the Python string has to be kept alive during a ctypes call.
  5. Decide for a web service whether the in-process or the subprocess route is right and say why.
  6. Read the linker error of the previous lesson and say what a -fPIC build fixes.

Questions

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

  1. What are the two routes from Python into Haskell?

    Answer

    A shared library through ctypes, or an executable through subprocess

    In process with ctypes, or out of process with subprocess.

  2. Which build produces the shared library that the ctypes client loads?

    Answer

    ghc -O1 -shared -dynamic -fPIC ... -lHSrts-1.0.2-ghc9.10.3

    The plain -shared command fails on the static archives; -dynamic links the shared versions and the runtime is named on the command line.

  3. What does lib.hs_init(None, None) do?

    Answer

    Starts the Haskell runtime before any exported call

    The runtime of the shared library has to be initialised by the host process.

  4. What does this program print? module Main (main) where import System.Environment (getArgs) main :: IO () main = do args <- getArgs print (length args) Run as ./count a b.

    Answer

    2

    Two arguments were passed and the program name is not counted.

  5. What does the measured subprocess call cost in this container?

    Answer

    About 2.6 milliseconds per call

    Fifty calls took 0.132 s, which is 2.64 ms each.

  6. What does this program print? module Main (main) where import System.Environment (getArgs) import Text.Read (readMaybe) main :: IO () main = do args <- getArgs case map readMaybe args :: [Maybe Int] of [Just a, Just b] -> print (a * b) _ -> putStrLn "usage" Run as ./mul 6 7.

    Answer

    42

    The two numbers are parsed and multiplied.

  7. Why must a Python string be kept alive during a ctypes call?

    Answer

    The C side holds a pointer to its bytes, not a copy

    A c_char_p points into the Python object, so collecting it during the call leaves a stale pointer.

  8. What does this program print? module Main (main) where main :: IO () main = print (sum [1 .. 5 :: Int])

    Answer

    15

    The sum of 1 to 5 is 15.

  9. When is the in-process route worth the shared library?

    Answer

    When the function is called many times and a process per call is too slow

    Milliseconds per process are fine for a few calls and hopeless for thousands.

  10. What does check=True do in subprocess.run?

    Answer

    Raises an exception on a non-zero exit status

    A failing call becomes an exception instead of a silent wrong answer.

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