Thanks for your explanation Albert, it makes things clearer.

So StablePtrs are just useful so that C code can:
1) call back into Haskell (through a foreign exported function like doSomethingWithTheObjectIGaveYou :: StablePtr MyObjectType -> Stuff -> IO ())
2) store them to return them later to Haskell when prompted (through a foreign imported function like getObject :: Stuff -> IO (StablePtr MyObjectType))
That's it?

But then,
In use case 1), how can a Haskell function modify the data addressed?

If StablePtrs cannot have their pointed value modified (either C or Haskell-side), that mostly limits their interest, doesn't it?


2012/2/12 Albert Y. C. Lai <trebla@vex.net>
On 12-02-12 09:18 AM, Yves Parès wrote:
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.

The doc multiply warns again and again that StablePtr, as well as whatever Ptr you get from castStablePtrToPtr, are opague (meaningless) to the C side. This is sanctioned by Haskell 2010, and GHC certainly exploits it to the fullest. The following example shows what kind of "pointer" values the C side receives for real (I deliberately do not free anything to show you more possible values):

#include <stdio.h>
void expose(void *p, void *q)
{
 printf("%p %p\n", p, q);
}

import Foreign.StablePtr
import Foreign.Ptr
main = do
 printout (0 :: Int)
 printout (let x = not x in x)
 printout ([] :: [Integer])
printout :: a -> IO ()
printout thunk = do
 p <- newStablePtr thunk
 expose p (castStablePtrToPtr p)
 -- I deliberately do not free
foreign import ccall expose :: StablePtr a -> Ptr b -> IO ()

Typically the output is like
0xf 0xf
0x10 0x10
0x11 0x11
Looks more like keys of a lookup table than pointers.

I do not know what good is castStablePtrToPtr for, given that StablePtr is already translated to C side void*, so that no intermediate Ptr step is necessary. Perhaps there is a story from a historical perspective.


_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe