Skip to content

Instantly share code, notes, and snippets.

@tfausak
Created May 29, 2014 15:24
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 tfausak/c3e2348f13e7a23c2add to your computer and use it in GitHub Desktop.
Save tfausak/c3e2348f13e7a23c2add to your computer and use it in GitHub Desktop.
A simple example of FFI in Haskell using the standard library, a source file, and a library.
{-# LANGUAGE ForeignFunctionInterface #-}
module Main (main) where
import Foreign.C.Types (CDouble (..))
foreign import ccall safe "math.h sin" c_sin :: CDouble -> CDouble
foreign import ccall safe "public.h square" c_square :: CDouble -> CDouble
foreign import ccall safe "private.h half" c_half :: CDouble -> CDouble
main :: IO ()
main = do
print $ sin 1.2
print $ c_sin 1.2
print $ 1.2 * 1.2
print $ c_square 1.2
print $ 1.2 / 2
print $ c_half 1.2
.PHONY: all build clean
all: build
build:
clang -c private.c
ghc --make Main.hs public.c private.o
clean:
rm -f Main Main.hi Main.o public.o private.o
double half ( double x ) { return x / 2 ; }
double half ( double x ) ;
double square ( double x ) { return x * x ; }
double square ( double x ) ;
@tfausak
Copy link
Author

tfausak commented May 29, 2014

# clang --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
# ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.6.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment