handles and foreign C functions

Hello, 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? TIA Andrea

On Wed, Dec 03, 2008 at 07:08:00PM +0300, Bulat Ziganshin wrote:
Hello Andrea,
Wednesday, December 3, 2008, 5:09:21 PM, you wrote:
How can I pass to printStuff a stdout FILE pointer?
afair, "&stdout" syntax used to import variables. it was discussed just a day or two ago :)
you mean this, I think: foreign import ccall unsafe "&stdout" c_stdout :: Ptr CFile (my fault with the cut&paste of the previous message). This is causing the segmentation fault I was talking about. Thanks, Andrea

Hello Andrea, Wednesday, December 3, 2008, 7:23:20 PM, you wrote: either some error in the code (i neevr used this feature) or stdout may be defile by a macro. can you try to define function for it: FILE *out() {return stdout;}
On Wed, Dec 03, 2008 at 07:08:00PM +0300, Bulat Ziganshin wrote:
Hello Andrea,
Wednesday, December 3, 2008, 5:09:21 PM, you wrote:
How can I pass to printStuff a stdout FILE pointer?
afair, "&stdout" syntax used to import variables. it was discussed just a day or two ago :)
you mean this, I think:
foreign import ccall unsafe "&stdout" c_stdout :: Ptr CFile
(my fault with the cut&paste of the previous message).
This is causing the segmentation fault I was talking about.
Thanks, Andrea _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
-- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com

Hello Bulat, On Wed, Dec 03, 2008 at 07:26:39PM +0300, Bulat Ziganshin wrote:
either some error in the code (i neevr used this feature) or stdout may be defile by a macro.
the second you said: /* C89/C99 say they're macros. Make them happy. */ (from stdio.h)
can you try to define function for it:
FILE *out() {return stdout;}
This does the trick. Thank you once again. Andrea
participants (2)
-
Andrea Rossato
-
Bulat Ziganshin