Safe Haskell | None |
---|---|
Language | Haskell2010 |
WGPU.Internal.Memory
Description
This module contains type classes used to manage marshalling of objects into memory before calling C functions.
Motivation
In many locations in the API, we have:
A type (example only) which contains a nice Haskell representation of some data:
data ApiType = ApiType { things :: Vector Thing }
and a raw type which is required for a C function:
data WGPUApiType = WGPUApiType { thingsCount ::Word8
, -- this is an array length things ::Ptr
WGPUApiThing -- this is a pointer to an array }
This type class constraint represents the ability to encode ApiType
as
WGPUApiType
, performing any necessary memory allocation and freeing:
ToRaw
ApiType WGPUApiType
ToRaw
uses the ContT
monad so that bracketing of the memory resources
can be performed around some continuation that uses the memory.
In the example above, we could write a ToRaw
instance as follows:
instanceToRaw
ApiType WGPUApiType whereraw
ApiType{..} = do names_ptr <-rawArrayPtr
namespure
$ WGPUApiType { namesCount = fromIntegral . length $ names, names = names_ptr }
The ToRawPtr
type class represents similar functionality, except that it
creates a pointer to a value. Thus it does both raw conversion and storing
the raw value in allocated memory. It exists as a separate type class so
that library types (eg. Text
and ByteString
) can be marshalled into
pointers more easily.
Classes
class ToRaw a b | a -> b where Source #
Represents a value of type a
that can be stored as type b
in the
ContT
monad.
Implementations of this type class should bracket any resource management for
creating the b
value around the continuation. For example. memory to hold
elements of b
should be allocated and freed in a bracketed fashion.
Methods
raw :: a -> ContT c IO b Source #
Convert a value to a raw representation, bracketing any resource management.
Instances
class ToRawPtr a b where Source #
Represents a value of type a
that can be stored as type (Ptr b)
in the
ContT
monad.
Implementations of this type class should bracket resource management for
creating (
around the continuation. In particular, the memory
allocated for Ptr
b)(
must be allocated before the continuation is
called, and freed afterward.Ptr
b)