Calling dynamically linked Haskell code from Rust

后端 未结 2 577
情深已故
情深已故 2021-01-04 02:17

I\'m trying to compile some Rust code with some Haskell code. I have a test system set up with a file, Fibonacci.hs with a function which computes fibonacci num

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 03:15

    When you compile your shared library, it looks like you need to link against libffi as well:

    ghc -o libfibonacci.dylib -shared -dynamic -fPIC \
      Fibonacci.hs wrapper.c -lHSrts -lffi
    

    I deduced this by going into my GHC library directory (/usr/local/lib/ghc-7.10.1/rts) and then grepping for the symbol ffi_call:

    $ grep -lRa ffi_call .
    ./include/ffi.h
    ./rts/libHSrts-ghc7.10.1.dylib
    ...
    

    I then used nm to find which exact library had it:

    for i in *dylib; do
       if nm $i | grep -q 'T.*ffi_call'; then
           echo "== $i";
       fi;
    done
    

    I was then able to run with:

    DYLD_LIBRARY_PATH='.' ./main
    

    Unfortunately, it appears your code isn't quite right, as I just get a bunch of empty tuples. You forgot to have a return type on the function, and then you run into a problem that the 46th or so Fibbonacci is too big for a u32.

    Additionally, you should be using the types from the libc package, and it may be safest to use a u64 here.

    I have installed GHC 7.10.1 using Homebrew, but hopefully the same pattern would work elsewhere.

提交回复
热议问题