jwiegley / c2hsc

Utility for creating .hsc files from C API header files
BSD 3-Clause "New" or "Revised" License
26 stars 15 forks source link

incorrect code generated for `char x[8][255]` #25

Open ghorn opened 9 years ago

ghorn commented 9 years ago

I have a struct like:

typedef struct {
    char listOfNames[8][255];
} MyCoolStruct;

I would expect that field to translate to type [Ptr CChar], which correctly happens, woohoo!

The problem is that I expect a list of length 8, where each Ptr CChar points to a character array with length 255. Instead I get a list of length 255, where the pointers are all invalid.

In the final haskell code, the deserialization looks like

instance Storable C'MyCoolStruct where
  peek p = do
    v0 <- peekArray (2040 `div` (sizeOf (undefined :: Ptr CChar)) (plusPtr p 0)
    return (C'MyCoolStruct v0)

which translates to

instance Storable C'MyCoolStruct where
  peek p = do
    v0 <- peekArray 255 p :: IO [Ptr CChar]
    return (C'MyCoolStruct v0)

This gives corrupt output. The pointers aren't valid pointers, they are strings cast to pointers. I think the correct implementation would be:

instance Storable C'MyCoolStruct where
  peek p = do
    let v0 = [plusPtr (plusPtr p 0) (255 * k) | k <- [0..8]]
    return (C'MyCoolStruct v0)

I looked through the source code but didn't make much progress. I'll be happy to try again if you can give me a few pointers to relevant sections.

ghorn commented 9 years ago

Btw, I wrote this issue from memory because I'm out of the office. I'll verify everything I wrote tomorrow.