c - How do I create a storable instance for this structure without c2hs or other tools? -
this structure:
typedef struct atom_ { float x; float y; float z; int col; } atom; corresponds type:
data atom = atom { pos :: v3 float, col :: int } how create storable instance atom can send atoms on haskell c function expects atom?
i can't guarantee work shown (i don't have environment set on computer), should first step towards getting right:
import foreign.storable import foreign.ptr instance storable atom -- don't make static, let compiler choose depending -- on platform sizeof _ = 3 * sizeof (0 :: float) + sizeof (0 :: int) -- may need fiddle this, , corresponding c -- code if have ability to, alignment can tricky, -- in case can pretty safely assume it'll alignment -- `float` alignment _ = alignment (0 :: float) -- these pretty straightforward, , order matters here -- great deal. haven't made optimized -- be, i'm going clarity of code instead peek ptr = let floatsize = sizeof (0 :: float) x <- peek $ ptr `plusptr` (0 * floatsize) y <- peek $ ptr `plusptr` (1 * floatsize) z <- peek $ ptr `plusptr` (2 * floatsize) col <- peek $ ptr `plusptr` (3 * floatsize) return $ atom (v3 x y z) col poke ptr (atom (v3 x y z) col) = let floatsize = sizeof (0 :: float) poke (ptr `plusptr` (0 * floatsize)) x poke (ptr `plusptr` (1 * floatsize)) y poke (ptr `plusptr` (2 * floatsize)) z poke (ptr `plusptr` (3 * floatsize)) col and should work! highly dependent on c compiler , platform, though, you'll want extensive testing make sure it's been laid out correctly.
Comments
Post a Comment