[Haskell-cafe] StablePtr's and castStablePtrToPtr
deejay at g615.co.uk
Tue Jul 25 22:16:54 EDT 2006
I have a query which is asked out of interest's sake...
I'm essentially looking for an affirmation of what I think I already
understand (or some info if I'm deluded ;)).
To put this in context...
I have some C code...
typedef int func(void *);
void from_maybe_int(void *val, func *my_func)
i = my_func(val);
printf("value within C: %d\n", i);
And some Haskell code...
type FromMaybeInt = StablePtr (Maybe Int) -> IO CInt
foreign import ccall "wrapper"
wrapFromMaybeInt :: FromMaybeInt
-> IO (FunPtr FromMaybeInt)
foreign import ccall "from_maybe_int"
cFromMaybeInt :: StablePtr (Maybe Int)
-> FunPtr GetJust
-> IO ()
functionToPass :: FromMaybeInt
functionToPass sPtr = do
m <- deRefStablePtr sPtr
case m of
Nothing -> return (-1)
Just i -> return (fromIntegral i)
main :: IO ()
main = do sPtr <- newStablePtr (Just 3) -- for example
funPtr <- wrapFromMaybeInt functionToPass
cFromMaybeInt sPtr funPtr
The compiled program works fine. However I wanted to check this was
correct usage. As in, is perfectly fine to pass a value of type
StablePtr a into C?
Am I correct in thinking that StablePtr is defined as a void pointer in
C? From my very limited understanding of C, it is also the case that you
can implicitly cast a void pointer to any other pointer type and
vice-versa. Some appear to deem it bad practice if you explictly give
So therefore I am somewhat hazy on the use for castStablePtrToPtr. I
found the ghc docs to be quite cryptic for this function.
Google dug up a few examples of it's use in PUGS... which has lead me to
think that the function is purely for type 'convience' in Haskell. Is
this the case or am I missing a use case here?
Disclaimer: My knowledge and experience of C is somewhat limited.
Ironically I have started playing with C by way of Haskell. (Sick and
twisted I know).
Thanks, Daniel James
P.S. I must say, I really like the Haskell FFI. Very clean and
enjoyable to work with.
More information about the Haskell-Cafe