How to create a persistent instance for this structure without c2hs or other tools?

This structure:

typedef struct Atom_ {
    float x;
    float y;
    float z;
    int col;
} Atom;

corresponds to this type:

data Atom = Atom { pos :: V3 Float, col :: Int }

How to create a persistent instance for Atomso that I can send Atomto Haskell for a C function that expects Atom?

+4
source share
1 answer

Currently, I can’t guarantee that it will work exactly as shown (I don’t have the environment installed on this computer), but this should be a good first step to the right right:

import Foreign.Storable
import Foreign.Ptr

instance Storable Atom where
    -- Don't make this static, let the compiler choose depending
    -- on the platform
    sizeOf _ = 3 * sizeOf (0 :: Float) + sizeOf (0 :: Int)
    -- You may need to fiddle with this, and with your corresponding C
    -- code if you have the ability to, alignment can be tricky, but
    -- in this case you can pretty safely assume it'll be the alignment
    -- for `Float`
    alignment _ = alignment (0 :: Float)
    -- These are pretty straightforward, and obviously order matters here
    -- a great deal.  I clearly haven't made this the most optimized it
    -- could be, I'm going for clarity of code instead
    peek ptr = do
        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) = do
        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 that should work! This may depend heavily on your C compiler and your platform, however you will want to conduct rigorous testing to make sure it is laid out correctly.

+3
source

All Articles