Skip to content

Instantly share code, notes, and snippets.

@wavewave
Created October 5, 2018 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wavewave/ee894ecf340ffe0fa8467f842618b6fc to your computer and use it in GitHub Desktop.
Save wavewave/ee894ecf340ffe0fa8467f842618b6fc to your computer and use it in GitHub Desktop.
rm *.o
rm test
ghclib=$(dirname $(which ghc))/../
ghc -fPIC -static -c Foo.hs
gcc -c test.c -I$ghclib/lib/ghc-8.2.2/include
ghc -o test test.o Foo.o -no-hs-main
#executation
./test
module Foo where
import Foreign.C.Types (CInt(..))
import Foreign.Ptr (Ptr,FunPtr)
func :: CInt -> CInt -> CInt
func j i = j + i+1
foreign import ccall "wrapper" mkFPtr :: (CInt -> CInt) -> IO (FunPtr (CInt -> CInt))
-- dynamic is inverse of wrapper
foreign import ccall "dynamic" mkFun :: FunPtr (CInt -> CInt) -> CInt -> CInt
foreign export ccall baz :: IO (FunPtr (CInt -> CInt))
baz :: IO (FunPtr (CInt -> CInt))
baz = do
putStrLn "I am baz!!"
fptr <- mkFPtr (func 20)
pure fptr
foreign export ccall qux :: FunPtr (CInt -> CInt) -> IO ()
qux :: (FunPtr (CInt -> CInt)) -> IO ()
qux fptr =
print $ mkFun fptr 11
#include <stdio.h>
#include "Foo_stub.h"
int main( int argc, char** argv ) {
hs_init( &argc, &argv );
int(*f)(int);
f = baz();
// C side call
int r = f(1);
printf("r = %d\n",r);
// Haskell side call
qux(f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment