Skip to content

Instantly share code, notes, and snippets.

@notcome
Created May 5, 2017 03:49
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 notcome/5b1f999cf82332820850c5f479a3fb20 to your computer and use it in GitHub Desktop.
Save notcome/5b1f999cf82332820850c5f479a3fb20 to your computer and use it in GitHub Desktop.
Play with FFI in Haskell
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Lib where
import Data.Word
import Foreign
import Foreign.C.Types
import Foreign.C.Error
import Foreign.C.String
foreign import ccall "open" cOpenFile :: CString -> CInt -> IO CInt
#define O_RDWR 0x0002
#define O_CREAT 0x0200
foreign import ccall "close" cCloseFile :: CInt -> IO ()
foreign import ccall "write" cWriteFile :: CInt -> Ptr () -> Word -> IO Word
newtype FileDescriptor = FileDescriptor { unFD :: CInt }
getFileDescriptor :: String -> IO FileDescriptor
getFileDescriptor path = do
pathCStr <- newCString path
fd <- cOpenFile pathCStr 0x0202
free pathCStr
if fd == -1
then throwErrno "fd == - 1"
else return $ FileDescriptor fd
deleteFileDescriptor :: FileDescriptor -> IO ()
deleteFileDescriptor descriptor = cCloseFile $ unFD descriptor
writeToFileDescriptor :: FileDescriptor -> String -> IO ()
writeToFileDescriptor (FileDescriptor fd) string = withCStringLen string helper
where
helper :: (CString, Int) -> IO ()
helper (cstr, length) = do
let ulen = (fromIntegral length) :: Word
cWriteFile fd (castPtr cstr) ulen
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment