Write a C function and Call the C function from Haskell
1. Write your C function in AronCLibFFI.c
void print_ascii(){
for(int i = 0; i < 127; i++){
printf("%d 0x%x %c\n", i, i, i);
}
}
2. Add AronCLibFFI.c full path in your cabal file: haskellffi.cabal
executable haskellffi
hs-source-dirs: src
main-is: Main.hs
default-language: Haskell2010
+ ---> contains print_ascii()
↓
c-sources: /Users/aaa/myfile/bitbucket/haskellffi/AronCLibFFI.c
↑
+ ---> Main.c can find your C function
build-depends: base >= 4.7 && < 5,
3. In your Main.hs , write haskell function to match the C function in AronCLibFFI.c
foreign import ccall "print_ascii"
c_print_ascii :: IO()
f_print_ascii::IO()
f_print_ascii = c_print_ascii
4. Call your Haskell function in your Main.hs
Main = f_print_ascii
5. How to call your FFI function inside GHCi ,You need to load the C Object file (AronCLibFFI.o) when you start GHCi
stack ghci --ghci-options="/Users/aaa/myfile/bitbucket/haskellffi/AronCLibFFI.o"
How Haskell call C function
-- Here is simple code for FFI
--
import Foreign
import Foreign.C.Types
foreign import ccall unsafe "math.h sin"
c_sin :: CDouble -> CDouble
main = do
let c = c_sin 3.1415
print c
C String to Haskell String, Haskell String to C String
peekCString::CString -> IO String
newCString::String -> IO CString
Conversion between Haskell Type and C Type