Calling Haskell from Python
Two ways into Haskell from Python
A Python program that wants a Haskell function has two routes:
- In process: build the function into a shared library with foreign export and load it with ctypes. Fast, no process per call, and the library has to be built on the platform that loads it.
- Out of process: run the Haskell executable with subprocess and read its output. Slower per call, no build complications, and the process cannot corrupt the Python one.
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:
- 4 CPUs (nproc 4), an Intel Core i3-6006U, Alpine Linux 3.24.3, x86_64, in a Docker container.
- GHC 9.10.3, the library built with -O1 -shared -dynamic -fPIC and -lHSrts-1.0.2-ghc9.10.3.
- Python 3.14.10 from the image, no virtual environment and no third-party package.
- The container is shared, so a round can be disturbed by another process; the minimum is the number to trust.
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:
- Pass numbers by value and strings as bytes. A Python str is Unicode and a C char * is bytes, so the conversion is .encode() on one side and decode() on the other.
- The bytes must outlive the call. With ctypes, a c_char_p points at a Python object; if the object is garbage collected during the call the pointer is stale. Keep the object in a variable for the duration.
- A returned char * is owned by the callee or by the runtime, not by Python, so copying it with ctypes.string_at or a free on the Haskell side is the caller's decision and must be documented.
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
- Change the Haskell program to read two numbers from one line of stdin and call it once for ten pairs.
- Measure the same fifty calls with ./adder started once and fed all the pairs, and compare.
- Write the ctypes declaration for a function that takes a c_char_p and returns an int32.
- Explain why the Python string has to be kept alive during a ctypes call.
- Decide for a web service whether the in-process or the subprocess route is right and say why.
- 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.
-
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.
-
Which build produces the shared library that the ctypes client loads?
Answer
ghc -O1 -shared -dynamic -fPIC ... -lHSrts-1.0.2-ghc9.10.3The plain -shared command fails on the static archives; -dynamic links the shared versions and the runtime is named on the command line.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
What does
check=Truedo insubprocess.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