[MLton] [MLton-user] calling MLton from MLton via FFI

Henry Cejtin henry.cejtin at sbcglobal.net
Thu Mar 10 08:44:38 PST 2011


One  alternative  to  Wesley's  suggestion  (of  having  C  code  do the
offsetting) is to have the space getting passed between C and  MLton  be
from malloc instead of being from a MLton array.  That way it definitely
will never move.

Of course then you have to handle deallocation yourself and on the MLton
side can only use functions in MLton.Pointer to access it.






________________________________
From: Wesley W. Terpstra <wesley at terpstra.ca>
To: mlton at mlton.org
Sent: Thu, March 10, 2011 7:05:47 AM
Subject: [MLton] [MLton-user] calling MLton from MLton via FFI


On Wed, Mar 9, 2011 at 6:36 PM, Christopher Cramer <tsuyoshi at yumegakanau.org> 
wrote:

I need to call some C functions with a pointer to the middle of an array.
>The way I have been doing this is to create a function in ML, and export
>it, so that I can convert the array to a pointer and then add the offset.
>
>
Is this safe?

No.

The moment you call ML from C any pointers into the heap you previously held 
become invalid. You calling back into MLton via FFI is just a *really short* 
path through C. ;)

You cannot assume that the parameter pointer given to gzreadoffset is valid. The 
garbage collector might move it at any time.

A good way to achieve what you'd like to do is make the gzreadoffset as a small 
piece of C code:

int gzreadoffset(gzFile *f,  unsigned char* buf, int offset, int len) {
  gzread(f, buf+offset, len);
  // buf is still valid because we haven't called out to SML
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mlton.org/pipermail/mlton/attachments/20110310/10f988c5/attachment.html


More information about the MLton mailing list