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

Nicolas Trangez ikke at nicolast.be
Mon Nov 28 16:30:15 UTC 2022


On Mon, 2022-11-28 at 17:04 +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.

Next to the other replies, did you consider using `hsc2hs` to create
these bindings? Using the tool, you can use its `#{size ...}`,
`#{alignment ...}` and `#{peek ...}`/`#{poke ...}` helpers to implement
`Storable` for some C struct, without running a C compiler in your head
(e.g., taking padding into account to implement `sizeOf`).

See the docs
at https://ghc.gitlab.haskell.org/ghc/doc/users_guide/utils.html#writing-haskell-interfaces-to-c-code-hsc2hs.
Note `hsc2hs` is fully integrated in Cabal (use `Foo.hsc` as module
filename), no need to reach out to its CLI. You can find a simple
example of a Storable instance using it at
https://github.com/NicolasT/landlock-hs/blob/b5638684869ad4f85bea53f10a3f0b921f000202/landlock/internal/System/Landlock/Rules.hsc#L44.

Nicolas

> 
> My Haskell-level record is the following:
> 
> data SignedMessage = SignedMessage
>    { messageLength :: CSize
>    , messageForeignPtr :: ForeignPtr CUChar
>    , signatureForeignPtr :: ForeignPtr CUChar
>    }
> 
> 
> Here is the code of the Storable instance: 
> https://gist.github.com/Kleidukos/31346d067f309f2a86cbd97a85c0f1e8#file-signing-hs
> 
> And so I used `hedgehog-classes` to test the Storable instance.
> However, 
> all the tests fail with the same reason: Prelude.undefined:
> 
> https://gist.github.com/Kleidukos/31346d067f309f2a86cbd97a85c0f1e8#file-undefined_error-txt
> 
> The main problem (and that's certainly a red herring for me) is that
> the 
> `undefined` call comes frombase:Foreign.Marshal.Array.
> Which shouldn't be a problem, as it is not supposed to be evaluated!
> Yet apparently it is.
> 
> If you're interested to see the full code, it's located here: 
> https://github.com/haskell-cryptography/libsodium-bindings/blob/add-sel-package/sel/src/Sel/Signing.hs
> 
> I'm not sure how to proceed from here. What would be a good angle to 
> approach this?
> 
> Cheers,
> Hécate
> 



More information about the Haskell-Cafe mailing list