[Haskell-cafe] Stable pointers: use of cast to/from Ptr

Yves Parès yves.pares at gmail.com
Sun Feb 12 15:18:44 CET 2012


According to the documentation (
StablePtrs aims at being opaque on C-side.
But they provide functions to be casted to/from regular *void**'s.
Does that mean if for instance you have a StablePtr CInt you can cast it to Ptr
() and alter it on C-side?

void alter(void* data)
    int* x = (int*)data;
    *x = 42;


-- using 'unsafe' doesn't change anything.
foreign import ccall safe "alter"
    alter :: Ptr () -> IO ()

main = do
    sptr <- newStablePtr (0 :: CInt)
    deRefStablePtr sptr >>= print
    alter (castStablePtrToPtr sptr)  -- SEGFAULTS!
    deRefStablePtr sptr >>= print
    freeStablePtr sptr

But I tried it, and it doesn't work: I got a segfault when 'alter' is

Is it normal? Does this mean I can only use my pointer as opaque? (Which I
know to be working, as I already got a C function call back into Haskell
and pass it the StablePtr via a 'foreign export')
But in that case, what is the use of castStablePtrToPtr/castPtrToStablePtr,
as you can already pass StablePtrs to and from C code?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120212/66b8d516/attachment.htm>

More information about the Haskell-Cafe mailing list