[Haskell-cafe] Re: Can my type be allowed as return type in FFI?

Mauricio briqueabraque at yahoo.com
Wed Dec 10 11:17:26 EST 2008


 > > > foreign import "nameOfFunction" nameOfFunction
 > > >  :: IO MyType
 > >
 > > > 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. (...)

This would  solve half my problem.  Can I always  trust that? I've
been told before  that everytime a C function  returns a struct it
is actually  returning a pointer, but  I wasn't able  to find that
written  in stone  so that  I can  trust it  to be  valid anywhere
Haskell will run and for any return type (like a struct containing
just a char, for instance).

How does  that pointer work?  My  code didn't provide it  to the C
function, so, I believe I  don't have to deallocate it. Where does
the memory  it points to live?   Did Haskell FFI  engine gave that
pointer to  the C  function? How  much time is  it going  to live?
Enough so I can 'peek' it?

 > > 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.

OK. I've instances of Storable for all the appropriate types.

 > > If do recommend reading the  FFI spec. It's quite readable and
 > > explains a lot of the issues.

Sure. It helped a lot. Actually, I've been able to do everything I
needed so far with just the spec and Foreign.*.

 > I would also  add the chapter 17 of Real  World Haskell. you can
 > read it here:

Nice. It  shows unsafePerformIO. Some  functions returning structs
are  side effect  free.  I'm  writing bindings  I want  to  put on
hackage,  so what  do  you think  would  fit better  the taste  of
Haskell  programmers:  pure  functions  using  unsafePerformIO  or
IO functions?

Thanks,
Maurício



More information about the Haskell-Cafe mailing list