[MLton-user] FFI question: converting C strings to ML
John Reppy
jhr at cs.uchicago.edu
Mon Dec 4 15:38:36 PST 2006
The following situation is quite common, but I haven't been able to find
a simple way to handle it in MLton's FFI. Say that we have a C function
const char *getString (int name);
that returns either a pointer to a C-style nul-terminated string or 0
when there
is an error. I'd like to map the result to an ML string or an
exception.
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?
- John
More information about the MLton-user
mailing list