GHC Haskell foreign export to C: exception termination versus error-code return
0 reputation · 25 Mar 2022, 20:24 UTC
0 reputation · 25 Mar 2022, 20:24 UTC
I need C code to call a Haskell function exported through GHC's foreign export interface and reliably detect when the Haskell IO action throws an exception, without letting the exception bring down the whole process.
The Haskell 2010 FFI does not define a portable mapping from Haskell exceptions to C error codes. GHC's runtime may abort, unwind, or terminate the process when an exception escapes a foreign export, and the outcome can depend on runtime configuration and whether the calling C thread is bound. Raw heap pointers also require StablePtr or ForeignPtr, but the immediate uncertainty is exception handling across the boundary.
37775 reputation · 26 Mar 2022, 06:39 UTC
An uncaught Haskell exception that escapes a GHC foreign export does not surface as a C error code. GHC treats it as a fatal runtime event: the RTS reports the exception and terminates the process, so the C caller cannot reliably continue. Catch the exception inside Haskell and return a C-compatible error code instead.
foreign export ccall hs_run :: CInt -> IO CInt
hs_run :: CInt -> IO CInt
hs_run n = do
result <- try (realWork n)
case result of
Right _ -> return 0
Left e -> do
hPutStrLn stderr ("hs_run failed: " ++ displayException e)
return 1
realWork is the unsafe core; hs_run is the C-facing boundary.
Assumes GHC 9.x with hs_init/hs_exit and a direct C call to the exported stub. The exact exit code and message format are version-dependent; treat them as unconfirmed for your GHC release. Do not catch SIGABRT or use C++ try/catch to intercept RTS termination.
Missing diagnostic: do you need a human-readable error message passed back to C, or is a numeric code sufficient? That determines whether to add a message-buffer parameter.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.