我试图在Debian PC上从Common Lisp(sbcl版本1.2.4)调用Haskell(ghc版本7.6.3)。
Haskell代码为
{-# 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
并且C接口是
#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;
}
编译和链接是通过以下命令完成的:
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
在sbcl中,我使用quicklisp加载cffi,然后加载动态库
(cffi:load-foreign-library "~/work/test-haskell-lisp/libfoo.so")
当我调用函数foo
(cffi:foreign-funcall "foo" :int 3 :int)
我从sbcl收到错误“未处理的内存故障”。欢迎任何建议或想法。