[Haskell-cafe] allocation for "pure" FFI functions

Johannes Waldmann waldmann at imn.htwk-leipzig.de
Thu Oct 14 13:45:46 EDT 2010

Hi. I wonder how to do the following properly.

I have one (large) C  type, let's call it T,
and I want to sell it as an abstract type in Haskell.

I want to use C functions as if they were of type T -> T  
(pure function, returns a modified copy of the input)
and the question is, how to do the memory allocation for that,
in particular, how to avoid  IO  showing up 
in the (visible) types on the Haskell side:

I don't want IO because I don't want to declare some artificial
order of execution - instead I want lazy evaluation.
E.g., I might have some Haskell record with a T component
which may or may not be evaluated (accessed) at all.

I came up with two straightforward approaches that don't work:

Version 1: the C function does "malloc" on its own,
and returns a Ptr. So far, this is pure (no IO).
Problem: to make the "free" happen,
I need to add a finalizer in Haskell, and this is IO.

Version 2: allocation on the Haskell side with
mallocForeignPtr. Problem: this is already in IO.

Is there a solution? Workaround? Better approach?
If it boils down to unsafePerformIO, then where do I put it,
and what should I watch out for?


More information about the Haskell-Cafe mailing list