[Haskell-cafe] FFI and modifying haskell memory

Sven Panne Sven.Panne at aedion.de
Sat Oct 22 09:04:26 EDT 2005

Am Samstag, 22. Oktober 2005 01:42 schrieb John Meacham:
> On Fri, Oct 21, 2005 at 03:19:36PM +0100, Joel Reymont wrote:
> > Is there a particular reason why StablePtr cannot provide a "fixed"
> > memory address? Then 4 bytes of memory won't need to be allocated so
> > that C could write to them and C could just modify the Haskell variable.
> because haskell values don't have the same representation as C values.
> haskell values are pointers to updatable thunks. in any case 'with'
> just allocates 4 bytes on the stack (the same as a auto C declaration)
> so is quite speedy compared to what it would take to make a haskell
> value look like a C one. not to mention haskell values can't be
> modified.

2 tiny remarks:

 * In Simon's example the first parameter to 'with' (the initial buffer size) 
was missing, but I guess you've figured this out already. In general: If the 
pointer you're passing to C has "in" semantics, 'with' (or one of its 
variations) is your friend. For "in/out" semantics, use 'with' + 'peek', and 
for "out" semantics" use 'alloca' + 'peek'.

 * As already mentioned, StablePtr can even refer to something which has no 
direct C counterpart, like Haskell functions. Needing them in the C world 
seems strange at first, because there is nothing thrilling you can do with 
them but pass them back to Haskell. But there are actually some good uses for 
that, like interfacing to callback-based C APIs where some additional 
bookkeeping is needed.


More information about the Haskell-Cafe mailing list