The module MarshalUtils contains a set of useful utility routines for marshalling.
The following two routines combine storage allocation and marshalling for types in the Storable class (Section 5.35).
new :: Storable a => a -> IO (Ptr a) with :: Storable a => a -> (Ptr a -> IO b) -> IO b
The function new allocates storage for its argument using MarshalAlloc.malloc (Section 5.22), and then, stores its argument into the newly allocated area. The function with works similarly, but passes the newly allocated memory area to the functional given as the second argument. The object is destructed and the memory area is freed upon return of the functional. This happens even if the functional throws an exception.
GHC-specific implementation note: The function with is currently called withObject.
fromBool :: Num a => Bool -> a toBool :: Num a => a -> Bool
The functions fromBool and toBool are conversions between Haskell Boolean values and numeric representations of Boolean values, where False is represented by 0 and True by any non-zero value.
maybeNew :: ( a -> IO (Ptr a)) -> (Maybe a -> IO (Ptr a)) maybeWith :: ( a -> (Ptr b -> IO c) -> IO c) -> (Maybe a -> (Ptr b -> IO c) -> IO c) maybePeek :: (Ptr a -> IO b ) -> (Ptr a -> IO (Maybe b))
The function maybeNew transforms a combined allocation and marshalling combinator such that it accepts a value wrapped into the Maybe type. In case of, Nothing, no storage is allocated and Ptr.nullPtr returned (Section 5.29). The function maybeWith does the same for combined allocation and marshalling combinators bracketing a functional.
Finally, maybePeek transforms a peek combinator such that it yields Nothing if passed a Ptr.nullPtr.
withMany :: (a -> (b -> res) -> res) -> [a] -> ([b] -> res) -> res
Given a combined allocation and marshalling combinator, the function withMany applies it to all elements of a list of values that have to be marshalled individually.
copyBytes :: Ptr a -> Ptr a -> Int -> IO () moveBytes :: Ptr a -> Ptr a -> Int -> IO ()
The two functions copyBytes moveBytes are Haskell variants of the standard C library routines memcpy() and memmove(), respectively. As with their C counterparts, moveBytes allows the source and destination array to overlap, whereas copyBytes does not allow overlapping areas. Both functions take a reference to the destination area as their first, and a reference to the source as their second argument - i.e., the argument order is as in an assignment.