7

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.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Dimitris
  • 151
  • 9
  • `{NULL}` is a worrying argument. What about `{""}` instead? Also, try calling it from C's `main()` as well, to find out whether your problem is in the C->Haskell layer or the SBCL->C layer. – amalloy Aug 04 '18 at 06:57
  • The C-Haskell case is working with no problem, i.e. having a main in c and linking the exact same dynamic library. Also {""} didn't make any different. – Dimitris Aug 04 '18 at 07:09
  • Maybe add some printf to see where in your function the crash happens? Are you running sbcl in slime? If you are then maybe try at a command line (single thread) – Dan Robertson Aug 04 '18 at 15:51
  • The crash happens at fibonacci_hs. If I comment out that line the crash happens at hs_exit. When only hs_exit is commented out the program crashes at fibonacci_hs. These tests were performed without slime. – Dimitris Aug 04 '18 at 17:15
  • 3
    Update: With ghc version 8.0.1 and sbcl version 1.3.14 on a different debian pc the exactly same code and commands (except from the library numbers) works! – Dimitris Aug 09 '18 at 15:11
  • @Dimitris this is weird but I’m glad it worked. Perhaps you were somehow building your C program for one version of ghc and your Haskell program for another. Or maybe you had discovered a ghc bug which was fixed in a later version. – Dan Robertson Aug 12 '18 at 10:31

0 Answers0