Changes between Version 20 and Version 21 of BlockObjects


Ignore:
Timestamp:
Aug 26, 2011 5:48:56 AM (4 years ago)
Author:
chak
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • BlockObjects

    v20 v21  
    1212In C, we might use this function as described in Apple's introduction to blocks: [http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW2 Using a Block Directly].  We would like to be able to do the same in Haskell by declaring:
    1313{{{
    14 foreign import ccall "stdlib.h" qsort_b :: Ptr a -> CSize -> CSize -> (Ptr a -> Ptr a -> Int) -> IO ()
     14foreign import ccall "stdlib.h" qsort_b
     15  :: Ptr (StablePtr a)                                    -- pointer to array of stable Haskell values
     16  -> CSize                                                -- size of the array
     17  -> CSize                                                -- size of a stable pointer to Haskell
     18  -> (Ptr (StablePtr a) -> Ptr (StablePtr a) -> IO Int)   -- comparison function
     19  -> IO ()
    1520
    1621myCharacters = ["TomJohn", "George", "Charles Condomine"]
    1722}}}
    18 and then executing
     23Note that the arguments to the comparison function are pointers to the array elements that need to be compared.  Each of these array elements is, in turn, a stable pointer to a Haskell thunk.
     24
     25When then use the C function from Haskell as follows:
    1926{{{
    2027do {   -- convert a list of strings into a C array of stable pointers to those strings in the Haskell heap
     
    2633
    2734           -- invoke C land 'qsort_b' with a Haskell comparison function passed as a block object; mutates 'myCharactersArray'
    28        ; qsort_b myCharactersArray (length myCharacters) elemSize (\l r -> fromOrdering (l `compare` r))
     35       ; qsort_b myCharactersArray (length myCharacters) elemSize
     36           (\l r -> do { l <- deRefStablePtr =<< peek lPtr
     37                       ; r <- deRefStablePtr =<< peek rPtr
     38                       ; return $ fromOrdering (l `compare` r)
     39                       })
    2940
    3041           -- obtain the sorted list of stable pointers from the sorted array