Created
May 5, 2017 03:49
-
-
Save notcome/5b1f999cf82332820850c5f479a3fb20 to your computer and use it in GitHub Desktop.
Play with FFI in Haskell
This file contains hidden or 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
{-# 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