[Haskell-cafe] Question on proper use of Data.IORef

Captain Freako capn.freako at gmail.com
Fri Jun 22 18:18:44 CEST 2012

Okay, I get it now. Thanks to all of you for your quick replies!

So, here's what I need to do:

   1. My Haskell code gets called by a higher level C function and asked to
   initialize itself.
   2. As part of that initialization, I'm expected to return a pointer to
   an instance of a particular data structure, which gets created/initialized
   in Haskell.
   3. I create a stable pointer to a data structure instance, using *
   newStablePtr*, and return that pointer to the calling C function.
   4. The same C function then, at a later time, calls a different function
   in my Haskell code, sending it that very same pointer, and expects that
   code to modify the data structure pointed to, in place.

So, I wrote some code that looks like this:

secondFunction :: StablePtr DataStructure -> IO ()
secondFunction dsPtr = do
    ds <- deRefStablePtr dsPtr
    theRef <- newIORef ds
    writeIORef theRef newDs

which, of course, didn't work, because I didn't understand the true nature
of IORef.

*So, my question is: How do I do this? That is, how do I modify, in place,
a data structure, which I originally created and made stable, using a
pointer to that structure, which is being passed back to me, by the higher
level C function that is calling me?*

Thanks, all!

On Fri, Jun 22, 2012 at 8:43 AM, Max Rabkin <max.rabkin at gmail.com> wrote:

> On Fri, Jun 22, 2012 at 5:30 PM, Captain Freako <capn.freako at gmail.com>
> wrote:
> >  12 main = do
> >  13     let theValue = 1
> >  14     print theValue
> >  15     theValueRef <- newIORef theValue
> >  16     bump theValueRef
> >  17     return theValue
> theValue is a plain old immutable Haskell variable. "newIORef" creates
> an IORef whose initial value is equal to the argument; it doesn't
> create a pointer to the value or something like that. Change "return
> theValue" to "readIORef theValueRef" to extract the changed value in
> the IORef.
> --Max
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120622/eaf5b29e/attachment.htm>

More information about the Haskell-Cafe mailing list