[MLton-user] FFI, MacOS PPC, and 16-bit ints

Matthew Fluet fluet at tti-c.org
Tue Nov 27 12:02:31 PST 2007


On Tue, 27 Nov 2007, Dave Herman wrote:
> On PPC MacOS, I can't seem to mutate Int16.int refs from C via the FFI. The 
> program below successfully mutates the ordinary int ref to 42, but does not 
> mutate the Int16.int ref.
>
> Am I abusing the FFI somehow, or is it a bug in MLton?

It is a bug in MLton, failing to account for a big-endian target.  All 
objects in the heap are padded for alignment purposes, so an Int16.int ref 
is represented as a pointer to a 32-bit heap object, 16 bits of which 
correspond to the Int16.int and 16 bits of which are (ignored) junk. 
MLton does this packing/padding in a manner that is independent of the 
endianness of the target platform.  This has the unfortunate consequence 
that on a big endian platform, the int16_t* that C sees points to the 
16-bits of junk, not the 16-bits of Int16.int.

Knowing that, you could write your code like:
   void foo(SHORT thing[2]) {
     thing[0] = 42;
     thing[1] = 42;
   }
which would work on both little endian and big endian platforms.

But, it is a bug in MLton and should be fixed.



More information about the MLton-user mailing list