[MLton-user] FFI and pointer relocation

Vesa Karvonen vesa.a.j.k at gmail.com
Mon Nov 26 13:23:37 PST 2007

On Nov 26, 2007 6:50 PM, Dave Herman <dherman at ccs.neu.edu> wrote:
> If I pass a ref cell through the FFI to some C code which squirrels away
> the pointer and updates it much later, will that always be safe? Or will
> the GC potentially move the location of the ref cell?

GC may move the ref cell.  As a rule of thumb (unless you really know
what you are doing), any data you wish to modify on the C side should
be allocated from the C heap.  If you wish this stuff to work from
both SML/NJ and MLton, I recommend that you use ML-NLFFI (the learning
curve is a bit steep, but it works).

> I'm using this to pass a bool ref through the FFI as a sort of "mailbox"
> to be notified whenever a particular event has occurred. Then the SML
> code polls the mailbox during its event loop to check if it needs to
> refresh some data (console window size) that becomes stale when the
> event (console window resize) occurs. I'm not sure if this is the best
> approach; the polling isn't expensive since I have a blocking loop
> anyway, but maybe there's a more elegant solution to registering an
> observer with the FFI.

Hmm... Is there a C API for reading the console window size?  If that
is the case, then I would recommend simply calling that API through a
ML-NLFFI generated interface each time you need the size.  Can be made
to work with both SML/NJ and MLton.

If you need help with ML-NLFFI, please post the C API (necessary
function prototypes and type (forward) declarations) to the list, and
someone (probably me) can prepare a sample (of how to use ML-NLFFI)
and post it to the list.

-Vesa Karvonen

More information about the MLton-user mailing list