Derive Storable instances with GHC.Generics.

Latest on Hackage:

This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow to host generated Haddocks.

MIT licensed by Mateusz Kloczko


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


Revision history for derive-storable -- 2017-10-05

  • Fixed a bug with POSIX types enabled on non POSIX systems. -- 2017-07-19

  • Bumped to GHC 8.2.* -- 2016-12-07

  • Made the information about performance problems more visible in -- 2016-11-29

  • Fixed the bug with Foreign.Storable.Generic.Internal.Instances module.
  • Removed two tests related to numbering of fields. -- 2016-09-19

  • Changed the link in README to hackage repository. -- 2016-09-11

  • Changed generic-storable to derive-storable in
  • Added to the package -- 2016-09-08

  • First version. Released on an unsuspecting world.
Depends on 1 package:
Used by 1 package:
comments powered byDisqus