Changes between Version 5 and Version 6 of BlockObjects
- Timestamp:
- 08/12/11 06:14:41 (23 months ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
BlockObjects
v5 v6 10 10 qsort_b(void *base, size_t nel, size_t width, int (^compar)(const void *, const void *)); 11 11 }}} 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:12 In 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: 13 13 {{{ 14 14 foreign import ccall qsort_b "stdlib.h" :: Ptr a -> CSize -> CSize -> (Ptr a -> Ptr a -> Int) -> IO () 15 16 myCharacters = ["TomJohn", "George", "Charles Condomine"] 17 }}} 18 and then executing 19 {{{ 20 do 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 }}} 33 Here we compare entire strings and not just the first characters as in the C implementation. The marshalling function `fromOrdering` is defined as follows: 34 {{{ 35 fromOrdering :: Ordering -> Int 36 fromOrdering LT = -1 37 fromOrdering EQ = 0 38 fromOrdering GT = 1 15 39 }}} 16 40
