simonmar at microsoft.com
Fri Apr 25 11:51:55 EDT 2003
> > The question is, if newCString fails to get allocation to s1 or s2,
> > how must i handle this error?.
> Using the normal Haskell98 IOError mechanisms:
> More usefully, you can use the GHC extensions (also supported
> by Hugs):
Slight correction: the right library to use is Control.Exception:
GHC.Exception is not indended for external consumption, as is the case with all the GHC.* libraries except for GHC.Exts - the clue
is "Stability: internal" in the header. We should really omit these from the docs.
> of which the most useful are bracket and bracket_ which provide
> functionality like Java/C++'s try/finally syntax.
> bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
> bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
> main = bracket (newCString s1) free $ \p1 ->
> bracket (newCString s2) free $ \p2 ->
> let p3 = hstrL p2 p1
> in peekCString p3 >>= \s ->
> print s
> This code will take care to free the two strings even if an
> exception is raised.
In cases like the above, you almost certainly want to use withCString which also guarantees to free the string if an exception is
More information about the FFI