derive-storable: Derive Storable instances with GHC.Generics.

[ foreign, library, mit ] [ Propose Tags ]
Change log
Dependencies base (>=4.8 && <4.12) [details]
License MIT
Author Mateusz Kloczko
Revised Revision 1 made by mkloczko at Tue Mar 20 21:58:53 UTC 2018
Category Foreign
Home page
Source repo head: git clone -b master
Uploaded by mkloczko at Thu Oct 5 14:13:19 UTC 2017
Distributions NixOS:
Downloads 1953 total (27 in the last 30 days)
Rating (no votes yet) [estimated by rule of succession]
Your Rating
  • λ
  • λ
  • λ
Status Docs uploaded by user
Build status unknown [no reports yet]
Hackage Matrix CI

Derive Storable instances with GHC.Generics. The derived Storable instances have the same alignment as C structs.

[Skip to Readme]




Note: This package has metadata revisions in the cabal description newer than included in the tarball. To unpack the package including the revisions, use 'cabal get'.

Maintainer's Corner

For package maintainers and hackage trustees

Readme for derive-storable-

[back to package description]


Build Status

The derive-storable package allows you to automatically generate Storable instances for your datatypes. It uses GHC.Generics, which allows the coders to derive certain instances automatically. To derive a (G)Storable instance, the data-type has to:

  • have only one constructor.
  • all fields of the constructor need to be GStorable.
  • implement a Generic instance (derive (Generic))

Note on performance

There are some problems with performance of derived Storable instances. For now there exists a solution in form of GHC Core plugin - derive-storable-plugin.


Here's an example:

{-# LANGUAGE DeriveGeneric #-}

import Foreign.Storable
import Foreign.Storable.Generic
import Foreign.Ptr
import Foreign.Marshal.Alloc

import Generics.Deriving

data Position = Position {
   x :: Double, 
   y :: Double
} deriving (Show,Read, Generic)

instance GStorable Position

updatePosition :: Ptr Position -> Position -> IO ()
updatePosition ptr pos = poke ptr pos

main = do
    let val = Position 0.0 10.0
    ptr <- malloc :: IO (Ptr Position)      
    putStrLn "Created a ptr with value of"
    putStrLn =<< show <$> peek ptr
    updatePosition ptr val
    putStrLn "And now the value of ptr is:"   
    putStrLn =<< show <$> peek ptr