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

Hécate hecate at glitchbra.in
Mon Nov 28 17:54:39 UTC 2022


Hi Viktor, hi everyone,

Thanks again for the many useful answers.

I'll try to answers the questions asked in one email:

1. did you consider using `hsc2hs` to create these bindings?

I have to admit I stopped at c2hs when I found out it could not produce 
correct alignments for libsodium: https://github.com/haskell/c2hs/issues/272
I am now being told that hsc2hs asks the compiler directly so it's not 
problem, but that's eleven months after the fact :)

2. What's the use case here?

The use case is certainly my own partial worldview of how it all works. 
That being said one interesting thing is that peek & poke allow you to 
do IO, whereas Binary's Put and Get do not seem to allow me to do it 
(without cheating at least). And I couldn't find any instruction that 
said that it was okay to use unsafeDupablePerformIO (or similar) in Binary.

Have a nice rest of your day!

Cheers,
Hécate

Le 28/11/2022 à 17:42, Viktor Dukhovni a écrit :
> 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?
>
-- 
Hécate ✨
🐦: @TechnoEmpress
IRC: Hecate
WWW: https://glitchbra.in
RUN: BSD



More information about the Haskell-Cafe mailing list