[Ur] interfacing with C or other languages - example system
Adam Chlipala
adamc at impredicative.com
Sun Nov 28 14:52:59 EST 2010
Marc Weber wrote:
> First use case:
> I'd like to teach urweb to run arbitrary system commands.
>
Just to repeat what I said the last time someone brought this up: it is
impossible to support this in Ur/Web in the most general way, without
allowing for the possibility of some crazy behavior. The runtime system
feels free to restart program execution at any time, which wouldn't work
well with effectful commands that can't be undone.
I think it can still be an instructive example of data representation
with the FFI, so I'll address your more specific questions below.
> However there are two important return types:
> a) the stdout data (blob). Is there already a blob_to_str function? I
> didn't find it
>
I don't know which mathematical function you have in mind. Ur/Web uses
0-terminated C strings. Since blobs may contain 0 bytes, it's not
obvious what conversion behavior you want. (In any case, I don't think
there are any conversion functions between these types in the standard
library.)
> b) exit code.
>
> So how do I pass those two values back to ur?
>
I suggest defining a C struct containing all the values you want to
return. Then your C function would call uw_malloc() to allocate space
for the struct, and the function would return the allocated pointer.
The actual abstract type exported to Ur/Web applications would be
implemented as the C type of pointers to this struct. By "abstract
type," I'm referring to a type declared with a line like "type
myNewType" in the .urs file for your C FFI module.
> system: (cmd:string) (timeout:int) returning one of
> | Ok status blob
> | Timeout blob
>
Currently, Ur/Web doesn't allow C FFI functions to return values in
algebraic datatypes besides those that can be represented with C enums.
However, you can easily provide the same set of operations (as
additional C FFI functions) on a new abstract type.
More information about the Ur
mailing list