[Haskell-cafe] Stable pointers: use of cast to/from Ptr
Antoine Latter
aslatter at gmail.com
Sun Feb 12 16:51:41 CET 2012
On Sun, Feb 12, 2012 at 8:18 AM, Yves Parès <yves.pares at gmail.com> wrote:
> Hello,
>
> According to the documentation
> (http://hackage.haskell.org/packages/archive/base/4.5.0.0/doc/html/Foreign-StablePtr.html),
> 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
> called.
>
I think that 'castStablePtrToPtr' exists because many C APIs use
'void*' to mean 'opaque lump of data', and these exist to conform to
that sort of API.
Antoine
More information about the Haskell-Cafe
mailing list