[Haskell-cafe] Writing and testing a Storable instance for a record wrapping ForeignPtrs

Viktor Dukhovni ietf-dane at dukhovni.org
Mon Nov 28 16:42:34 UTC 2022


On Mon, Nov 28, 2022 at 05:04:32PM +0100, Hécate wrote:

> In a fit of madness I have found myself writing Haskell code where I 
> need to implement a Storable instance. However, by virtue of not being a 
> C programmer, I'm fairly lost on some of the details, especially the 
> value of the sizeOf and alignment methods.
> 
> My Haskell-level record is the following:
> 
> data SignedMessage = SignedMessage
>    { messageLength :: CSize
>    , messageForeignPtr :: ForeignPtr CUChar
>    , signatureForeignPtr :: ForeignPtr CUChar
>    }

This is not the sort of object for which `Storable` makes sense.  It
holds ephemeral pointers to variable sized external data, and so cannot
be serialised in a modest fixed-size memory block.  The `Storable` class
is for primitive data (Ints, Words, ...) and simple fixed layout
structures consisting of same (e.g. various structures passed to, or returned
by C system calls).  When structures contain pointers to data, nested
`peek` or `poke` calls (with associated memory allocations) may be needed
to read or write the structure.

To serialise your "SignedMessage" object you may need a higher-level
serialisation format.  ASN.1, protobufs, ... or (for a Haskell-only
format) an instance of `Data.Binary.Binary` (rather than Storable).

    https://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary.html

What's the use case here?

-- 
    Viktor.


More information about the Haskell-Cafe mailing list