Created
October 5, 2018 23:51
-
-
Save wavewave/ee894ecf340ffe0fa8467f842618b6fc 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
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 |
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 <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