Skip to content

Instantly share code, notes, and snippets.

@wavewave
Created October 5, 2018 23:13
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/214427502797acd2f2dd5271a708067f to your computer and use it in GitHub Desktop.
Save wavewave/214427502797acd2f2dd5271a708067f 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
{-# LANGUAGE ScopedTypeVariables #-}
module Foo where
import Foreign.Ptr (Ptr)
import Foreign.StablePtr (castStablePtrToPtr
,castPtrToStablePtr
,deRefStablePtr
,newStablePtr
)
foreign export ccall foo :: IO (Ptr ())
foo :: IO (Ptr ())
foo = do
putStrLn "I am foo!!"
sptr <- newStablePtr (3 :: Int)
pure $ castStablePtrToPtr sptr
foreign export ccall bar :: Ptr () -> IO ()
bar :: Ptr () -> IO ()
bar ptr = do
value :: Int <- deRefStablePtr $ castPtrToStablePtr ptr
print value
func :: Int -> Int
func i = i+1
foreign export ccall fooF :: IO (Ptr ())
fooF :: IO (Ptr ())
fooF = do
putStrLn "I am foo!!"
sptr <- newStablePtr func
pure $ castStablePtrToPtr sptr
foreign export ccall barF :: Ptr () -> IO ()
barF :: Ptr () -> IO ()
barF ptr = do
f :: Int -> Int <- deRefStablePtr $ castPtrToStablePtr ptr
print (f 10)
#include "Foo_stub.h"
int main( int argc, char** argv ) {
hs_init( &argc, &argv );
void* p = foo();
bar(p);
void* q = fooF();
barF(q);
/*
// The following segfaults.
//
int(*f)(int);
f = (int(*)(int)) fooF();
f(4);
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment