I am trying to call Haskell (ghc version 7.6.3) from Common Lisp (sbcl version 1.2.4) on a debian pc.
The Haskell code is
{-# LANGUAGE ForeignFunctionInterface #-}
module Safe where
import Foreign.C.Types
fibonacci :: Int -> Int
fibonacci n = fibs !! n
where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
fibonacci_hs :: CInt -> CInt
fibonacci_hs = fromIntegral . fibonacci . fromIntegral
foreign export ccall fibonacci_hs :: CInt -> CInt
and the C interface is
#include <HsFFI.h>
#ifdef __GLASGOW_HASKELL__
#include "Safe_stub.h"
extern void __stginit_Safe(void);
#endif
#include <stdio.h>
int foo(int i)
{
int argc = 0;
char *argv[] = {NULL};
char **pargv = argv;
int f;
hs_init(&argc, &pargv);
#ifdef __GLASGOW_HASKELL__
hs_add_root(__stginit_Safe);
#endif
f = fibonacci_hs(i);
hs_exit();
return f;
}
Compile and linking is done by the following commands:
ghc -c -dynamic -fPIC Safe.hs
gcc -c -fPIC -I`ghc --print-libdir`/include foo.c
ghc -o libfoo.so -dynamic -shared -lHSrts-ghc7.6.3 Safe.o foo.o
In sbcl, I load cffi with quicklisp, and then load the dynamic library
(cffi:load-foreign-library "~/work/test-haskell-lisp/libfoo.so")
When I call the function foo
(cffi:foreign-funcall "foo" :int 3 :int)
I get the error "Unhandled memory fault" from sbcl. Any suggestions or ideas are welcome.