[MLton] Callback to function pointer?

Wesley W. Terpstra wesley@terpstra.ca
Thu, 14 Jul 2005 11:48:20 +0200

On Wed, Jul 13, 2005 at 09:08:03AM -0400, Matthew Fluet wrote:
> For FFI _import, we currently have the following:
>   (* A. fetch a simple FFI object (when evaluated) *)
>   _import "name" : ffiTy;

Another dumb FFI question: why can't we export a constant?

Essentially, _export "foo": 'a; gives 'a -> unit for a type, right?

So, _export "foo": int -> unit; returns a setter function for the symbol
"foo" with type (int -> unit) -> unit. Furthermore, MLton will emit the
symbol "foo" so that C can link against it. What I wonder is why doesn't
_export "foo": int; return a setter for the symbol "foo" with type 
int -> unit?

I can think of a couple cases where being able to set a C global variable
would be useful. The only question is whether or not MLton should create
the symbol as well as set it. Perhaps 'weak' symbols are useful here.

int myglobal = 4;
fun dowork x = (_export "myglobal": int; 5; more_stuff...)

Here the global variable from C gets set.

The alternative, perhaps more in line with the word 'export', is for 
MLton to create it's own "myglobal" symbol and set it. (like for functions)

extern int myglobal;
int myfun() { printf("%d\n", myglobal); return 0; }
fun dowork x = (_export "myglobal": int; x; _import "myfun": unit -> int; ())

An amusing example of abuse of this syntax:

  val setter = _export "faster_sneaky_hack": Posix.IO.file_desc;
  fun getFD fd = (setter fd; _import "faster_sneaky_hack": int;)

Wesley W. Terpstra