[Haskell-cafe] handles and foreign C functions

Andrea Rossato mailing_list at istitutocolli.org
Wed Dec 3 09:09:21 EST 2008


suppose a simple C function like this:

void printStuff(FILE *f)
    fprintf (f, "Hello World\n");

In order to use it I need to import fopen and pass to it a Ptr CFile:

foreign import ccall unsafe "fopen"  fopen  :: CString -> CString -> IO (Ptr CFile)
foreign import ccall unsafe "fclose" fclose :: Ptr CFile -> IO CInt

foreign import ccall unsafe "printStuff" printStuff :: Ptr CFile -> IO ()

main =
  withCString "tmp.txt" $ \cpath  ->
  withCString "w"       $ \cmode  -> do
    cfile <- throwErrnoIfNull "fopen: " (fopen cpath cmode)
    printStuff cfile
    fclose cfile

How can I pass to printStuff a stdout FILE pointer?

If, for instance, I do:

foreign import ccall unsafe "stdout" c_stdout :: Ptr CFile
main =
  withCString "tmp.txt" $ \cpath  ->
  withCString "w"       $ \cmode  -> do
    printStuff c_stdout

I get a segmentation fault.

What am I missing?


More information about the Haskell-Cafe mailing list