Go to the first, previous, next, last section, table of contents.

Subverting automatic unboxing with "stable pointers"

The arguments of a `_ccall_' are automatically unboxed before the call. There are two reasons why this is usually the Right Thing to do:

It is possible to subvert the unboxing process by creating a "stable pointer" to a value and passing the stable pointer instead. (To use stable pointers, you must `import PreludeGlaMisc'.) For example, to pass/return an integer lazily to C functions `storeC' and `fetchC', one might write:

storeH :: Int -> PrimIO ()
storeH x = makeStablePtr x              `thenPrimIO` \ stable_x ->
           _ccall_ storeC stable_x

fetchH :: PrimIO Int
fetchH x = _ccall_ fetchC               `thenPrimIO` \ stable_x ->
           deRefStablePtr stable_x      `thenPrimIO` \ x ->
           freeStablePtr stable_x       `seqPrimIO`
           returnPrimIO x

The garbage collector will refrain from throwing a stable pointer away until you explicitly call one of the following from C or Haskell.

void freeStablePointer( StgStablePtr stablePtrToToss )
freeStablePtr :: _StablePtr a -> PrimIO ()

As with the use of `free' in C programs, GREAT CARE SHOULD BE EXERCISED to ensure these functions are called at the right time: too early and you get dangling references (and, if you're lucky, an error message from the runtime system); too late and you get space leaks.


Go to the first, previous, next, last section, table of contents.