foreign import wrinkles
foreign import function is safe. A safe
external function may cause a garbage collection as a result of being
called. If the programmer can guarantee that the external call
will not cause a GC to happen, it can be marked as unsafe (see
Section
Calling foreign functions
for details of how to do this.)
Unsafe calls are cheaper than safe ones, so distinguishing the two
classes of external calls may be worth your while if you're conscious
about performance.
foreign import "mumble" mumble :: ForeignObj -> IO ()
f :: Addr -> IO ()
f ptr = do
fo <- makeForeignObj ptr myFinalizer
mumble fo
The ForeignObj must live across the call to mumble even if
it is not subsequently used/reachable. Why the insistence on this?
Consider what happens if mumble calls a function which calls back
into the Haskell world to execute a function, behind our back as it
were. This evaluation may possibly cause a garbage collection, with
the result that fo may end up being finalised.
By guaranteeing that fo will be considered live across the call
to mumble, the unfortunate situation where fo is finalised
(and hence the reference passed to mumble is suddenly no longer
valid) is avoided.