[MLton-user] FFI question: converting C strings to ML

Stephen Weeks sweeks at sweeks.com
Mon Dec 4 15:56:25 PST 2006


> Right now, my code is
> 
> 	val charPtr = getString(name)
> 	val mlString = if (MLton.Pointer.null = charPtr)
> 	      then let
> 		val len = strlen charPtr
> 		val buf = CharArray.array(len, #" ")
> 		val _ = strncpy (buf, charPtr, len)
> 		in
> 		  CharArray.vector buf
> 		end
> 	      else raise Fail "null pointer"
> 
> where getString, strlen, and strncpy are imported C functions.  Is  
> there a better
> way to do this conversion?

I typically do the equivalent to your code, but without imported the
"strlen" and "strncpy".  Instead I use MLton.Pointer.getWord8 and
CharVector.tabulate in SML.  See code below.

BTW, it looks like your code has the null test reversed.

----------------------------------------------------------------------

signature C_STRING = sig
   type t

   val isNull: t -> bool
   val size: t -> int
   val sub: t * int -> char
   val toString: t -> string
end

structure CString:> C_STRING = struct

   structure Pointer = MLton.Pointer

   type t = Pointer.t

   fun isNull s = s = Pointer.null

   fun sub (s, i) = Byte.byteToChar (Pointer.getWord8 (s, i))
      
   fun size s = let
      fun loop i = if #"\000" = sub (s, i) then i else loop (i + 1)
   in
      loop 0
   end
      
   fun toString s =
      if isNull s then
         raise Fail "CString.toString"
      else
         CharVector.tabulate (size s, fn i => sub (s, i))

end



More information about the MLton-user mailing list