
On 16/06/2020 16:44, ☂Josh Chia (謝任中) wrote:
Based on my limited understanding of Haskell FFI according to the Haskell 2010 Language Report (https://www.haskell.org/onlinereport/haskell2010/haskellch8.html), it is not possible to have a ccall for makeFoo() because Foo is not a marshallable foreign result type. Is my understanding correct?
Yes. Structures are sometimes passed into registers (at least on x86-64) depending on their field types. GHC doesn't support this.
However, I believe I can have a ccall if I change makeFoo() to either of the following: Foo* makeFoo(size_t x); void makeFoo(Foo* out, size_t x);
The first involves the C code allocating a Foo and returning a pointer to it (so now there's one more pointer for the C code to deallocate later in another function). The second involves the C code writing a Foo value to a piece of memory allocated in Haskell (possibly using Foreign.Marshall.Alloc.alloca). Both signatures work because Foo* is marshallable but are clumsier to use than the original signature. Is there just no way to return a struct by value on the stack? Is there a cleaner way than the above two?
The second approach seems cleaner to me. With a Storable instance for Foo, it's not that much clumsy. Sylvain