Next Previous Contents

14.1 Stable Pointers

A stable pointer is a reference to a Haskell expression that can be passed to foreign functions via the foreign function interface.

Normally a Haskell object will move around from time to time, because of garbage collection, hence we can't just pass the address of an object to a foreign function and expect it to remain valid. Stable pointers provide a level of indirection so that the foreign code can get the "real address" of the Haskell object by calling deRefStablePtr on the stable pointer object it has.

The Haskell interface provided by the Stable module is as follows:

data StablePtr a  -- abstract, instance of: Eq.
makeStablePtr  :: a -> IO (StablePtr a)
deRefStablePtr :: StablePtr a -> IO a
freeStablePtr  :: StablePtr a -> IO ()

Care must be taken to free stable pointers that are no longer required using the freeStablePtr function, otherwise two bad things can happen:

Notes:

The C interface (which is brought into scope by #include <Stable.h>) is as follows:

typedef StablePtr /* abstract, probably an unsigned long */
extern StgPtr         deRefStablePtr(StgStablePtr stable_ptr);
static void           freeStablePtr(StgStablePtr sp);
static StgStablePtr   splitStablePtr(StgStablePtr sp);

The functions deRefStablePtr and freeStablePtr are equivalent to the Haskell functions of the same name above.

The function splitStablePtr allows a stable pointer to be duplicated without making a new one with makeStablePtr. The stable pointer won't be removed from the runtime system's internal table until freeStablePtr is called on both pointers.


Next Previous Contents