[Haskell-cafe] Stable pointers: use of cast to/from Ptr
Yves Parès
yves.pares at gmail.com
Sun Feb 12 21:53:15 CET 2012
Yes, but from C side, a StablePtr* is **already a **void**. (See HsFFI.h
which typedefs HsStablePtr to void*)
So its sufficient for a use as an opaque pointer, no need to cast it.
So what is the use of casting it to a Ptr () if this doesn't allow to
access the memory space addressed?
2012/2/12 Antoine Latter <aslatter at gmail.com>
> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120212/b732b4f7/attachment.htm>
More information about the Haskell-Cafe
mailing list