[Haskell-cafe] Can my type be allowed as return type in FFI?
duncan.coutts at worc.ox.ac.uk
Wed Dec 10 07:30:56 EST 2008
On Wed, 2008-12-10 at 08:33 -0200, Mauricio wrote:
> When I do:
> foreign import "nameOfFunction" nameOfFunction
> :: IO MyType
> I can get a function that return MyType only if
> it's a pointer or some of the C* type family. Is
> it possible to write a new MyType and make it
> allowed as a return type from foreign functions?
> Is changing the compiler the only way to do that?
Of course you're not really returning a MyType but a pointer to one. So
foreign import "nameOfFunction" nameOfFunction
:: IO (Ptr MyType)
Using raw Ptrs is not very nice, so we would usually either wrap that in
a ForeignPtr or use a Storable instance to get a MyType directly. Which
approach to use depends on if you want MyType to have value or reference
semantics. If the C type is abstract and you only access it via a
pointer then the ForeignPtr approach is sensible. If you directly access
all the fields of the C type then using an equivalent Haskell MyType and
converting using Storable is the sensible approach.
If do recommend reading the FFI spec. It's quite readable and explains a
lot of the issues. Getting familiar with the Foreign libraries will help
too. The most important bits are understanding ForeignPtr and the
More information about the Haskell-Cafe