Changes between Version 5 and Version 6 of BlockObjects


Ignore:
Timestamp:
Aug 12, 2011 1:14:41 PM (4 years ago)
Author:
chak
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • BlockObjects

    v5 v6  
    1010qsort_b(void *base, size_t nel, size_t width, int (^compar)(const void *, const void *));
    1111}}}
    12 In C, we might use this function as described in Apple's introduction to block: [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 writing:
     12In 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{{{
    1414foreign import ccall qsort_b "stdlib.h" :: Ptr a -> CSize -> CSize -> (Ptr a -> Ptr a -> Int) -> IO ()
     15
     16myCharacters = ["TomJohn", "George", "Charles Condomine"]
     17}}}
     18and then executing
     19{{{
     20do
     21    -- convert a list of strings into a C array of stable pointers to those strings in the Haskell heap
     22  myCharactersArray <- newArray $ mapM newStablePtr myCharacters
     23 
     24   -- get the size in bytes of a stable pointer to a Haskell string
     25  let elemSize = fromInteger $ sizeof (undefined :: StablePtr String)
     26
     27    -- 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))
     29
     30    -- turn the array of Haskell strings back into a list of strings
     31  mySortedCharacters <- mapM deRefStablePtr myCharactersArray
     32}}}
     33Here we compare entire strings and not just the first characters as in the C implementation.  The marshalling function `fromOrdering` is defined as follows:
     34{{{
     35fromOrdering :: Ordering -> Int
     36fromOrdering LT = -1
     37fromOrdering EQ = 0
     38fromOrdering GT = 1
    1539}}}
    1640