Created
October 5, 2018 23:13
-
-
Save wavewave/214427502797acd2f2dd5271a708067f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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