Advertisement
yuroru

a FFI example exporting Haskell functions

Dec 22nd, 2015
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE ForeignFunctionInterface #-}
  2.  
  3. module Array where
  4.  
  5. import Foreign.Ptr
  6. import Foreign.Storable
  7.  
  8. hs_f_int :: Ptr Int -> IO ()
  9. hs_f_int p = do
  10.     x <- peek p
  11.     let y = x + 1
  12.     poke p y
  13.  
  14. hs_f_int2 :: Ptr Int -> IO ()
  15. hs_f_int2 p = do
  16.     x <- peek p
  17.     let x' = x + 1
  18.    poke p x'
  19.     y <- peek ((plusPtr p 4) :: Ptr Int)  -- to decide a type
  20.     let y' = y + 1
  21.    poke (plusPtr p 4) y'
  22.  
  23. hs_f_int3 :: Ptr Int -> IO ()
  24. hs_f_int3 p = do
  25.     x <- peek p
  26.     let x' = x + 1
  27.    poke p x'
  28.     y <- peek (plusPtrInt p 1)
  29.     let y' = y + 1
  30.    poke (plusPtrInt p 1) y'
  31.     z <- peek (plusPtrInt p 2)
  32.     let z' = z + 1
  33.    poke (plusPtrInt p 2) z'
  34.  
  35. --hs_get_array_int :: Ptr Int -> Int -> IO ()
  36. --hs_get_array_int p n = do
  37.  
  38. plusPtrInt :: Ptr Int -> Int -> Ptr Int
  39. plusPtrInt p n = plusPtr p (4 * n)
  40.  
  41. foreign export ccall hs_f_int :: Ptr Int -> IO ()
  42. foreign export ccall hs_f_int2 :: Ptr Int -> IO ()
  43. foreign export ccall hs_f_int3 :: Ptr Int -> IO ()
  44.  
  45. /* C program calling above code is below */
  46.  
  47. #include <HsFFI.h>
  48. #ifdef __GLASGOW_HASKELL__
  49.     #include "Array_stub.h"
  50.     extern void __stginit_Array(void);
  51. #endif
  52.  
  53. #include <stdio.h>
  54.  
  55. void print_array(int a[], int n);
  56.  
  57. int main()
  58. {
  59.     int x;
  60.     int *p;
  61.     int a[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
  62.  
  63.     hs_init(NULL, NULL);
  64.     #ifdef __GLASGOW_HASKELL__
  65.         hs_add_root(__stginit_Array);
  66.     #endif
  67.  
  68.     x = 2;
  69.     p = &x;
  70.  
  71.     printf("%d\n", *p);  // 2
  72.     hs_f_int(p);
  73.     printf("%d\n", *p);  // 3
  74.  
  75.     print_array(a, sizeof a / sizeof (int));  // 2 3 5 7 11 13 17 19 23 29
  76.     hs_f_int2(a);
  77.     print_array(a, sizeof a / sizeof (int));  // 3 4 5 7 11 13 17 19 23 29
  78.  
  79.     printf("\n");
  80.  
  81.     print_array(a, sizeof a / sizeof (int));  // 3 4 5 7 11 13 17 19 23 29
  82.     hs_f_int3(a);
  83.     print_array(a, sizeof a / sizeof (int));  // 4 5 6 7 11 13 17 19 23 29
  84.  
  85.     hs_exit();
  86.     return 0;
  87. }
  88.  
  89. void print_array(int a[], int n)
  90. {
  91.     int i;
  92.  
  93.     for (i = 0; i < n; i++)
  94.         printf("%d ", a[i]);
  95.     printf("\n");
  96. }
  97.  
  98. # to compile in Windows, type:
  99. >ghc -c Array.hs
  100. >ghc --make -no-hs-main -optc-O main.c Array -o main.exe
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement