haskell / c2hs

c2hs is a pre-processor for Haskell FFI bindings to C libraries
http://hackage.haskell.org/package/c2hs
Other
197 stars 50 forks source link

Function hooks not using provided type for marshaling #251

Open drone29a opened 4 years ago

drone29a commented 4 years ago

Assuming a C function prototype like: bool getFooAtIndex(Ctx *ctx, uint64_t index, Foo *foo); where the return value indicates whether the call was successful. And when successful, the Foo structure pointed to by *foo should have it's Foo fields set appropriately. Foo is non-opaque, that is, we know the definition and we have a corresponding Haskell type and this type has a Storable instance.

How would we use c2hs to describe the bindings for this function?

My initial attempt looks like:

  {withPtr* `Ctx', fromIntegral `Word64', alloca- `Foo' peek*} -> `Bool' toBool #}

I then expect a getFoo function in Haskell with the type: Ctx -> Word64 -> IO (Bool, Foo)

However, it appears c2hs doesn't use the type Foo provided in the third param description of the function hook to determine how much space to allocate or the type to return. So as is, this won't compile.

I can get the bindings to build if I swap out peek* for a custom out-marshaller which converts a Ptr () to a Ptr Foo. However, my concern is that if alloca thinks the type is Ptr () then it is not using Foo's size (from Storable) to allocate memory. Maybe worth noting that while there is aStorable instance for Foo, there is no Pointer instance.

Any ideas or suggestions where I could find an example to examine?