On Tue, Sep 01, 2020 at 09:27:39AM -0500, Eric Blake wrote:
I guess my remaining questions are whether there is a better approach than:
func : export list = [ { "name1"; None }; { "name2"; Some "desc" } ]
In python, I was able to use:
return [ "name1", ( "name2", "desc" ) ]
where the alternation was on a string vs. a 2-tuple of strings, rather than all list members being a record but where the record had an optional member. But I'm not sure how to represent that in the ocaml interface. Maybe I'm thinking of something like:
type export = | Name of string | NameDesc of string * string
but I'm not quite sure how to write a list that initializes that. On the other hand, I think I understand the C binding for such a type: either val is Val_int(0) (C 1) for the Name branch (Field(v, 0) is a string), or val is Val_int(1) (C 2) for the NameDesc branch (Field(v, 0) is name, Field(v, 1) is desc).
Using optional fields in a struct (your original implementation) is fine and perfectly natural. If you really wanted to use the Name/NameDesc version then you'd write that in OCaml as: [ Name "name1"; NameDesc ("name2", "desc") ] and on the C side each element of the list would be a block with tags 0 (Name) or 1 (NameDesc), and 1 or 2 fields respectively. The way constructors are stored is complicated and optimized for fast access rather than ease of unpacking for C programmers. If you really want the details it's at the bottom of: https://rwmj.wordpress.com/2009/08/05/ocaml-internals-part-2-strings-and-oth... or in the official manual here: https://caml.inria.fr/pub/docs/manual-ocaml/intfc.html#ss:c-concrete-datatyp... Rich. -- Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones Read my programming and virtualization blog: http://rwmj.wordpress.com Fedora Windows cross-compiler. Compile Windows programs, test, and build Windows installers. Over 100 libraries supported. http://fedoraproject.org/wiki/MinGW