English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Accessing constructors (tags) from C
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-11-23 (18:42)
From: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] Accessing constructors (tags) from C
See Section 18.3.4 of the manual. In your example below, Null is an integer
0 and Int is a 1-word block with tag 1. In C, Null is Val_int(0) and t =
Int(x) is caml_alloc(1, 1); Store_field(t, 0, Val_int(x)).

In general, the first constructor is 0 and so on in the order specified in
the type declaration in ML. It is therefore *very* important to put a note
in your .mli file that the order of the constructors matters because you're
using it from C bindings. If you want to do this automatically, you'll need
to write a pre-processor (a camlp4 filter can probably help you build a .h
file that you can #include in your C files if you want to do it symbolically
- I've never had to write C bindings large enough to worry about the
fragility of sum types).

Note that polymorphic variants have a completely different representation
explained in 18.3.6 in the reference manual.


> -----Original Message-----
> From: caml-list-bounces@yquem.inria.fr [mailto:caml-list-
> bounces@yquem.inria.fr] On Behalf Of Raj Bandyopadhyay
> Sent: 23 November 2008 18:23
> To: caml-list@yquem.inria.fr
> Subject: [Caml-list] Accessing constructors (tags) from C
> Hi all
> I was wondering how to access constructors from C. For example if I
> define a type
> type t = Null | Int of int
> and I want to create values of type t in C using the OCaml-C interface,
> how do I find
> the integers corresponding to constructors Null or Int? I would like to
> do this for a large OCaml program with lots of different types etc.
> Thanks!
> Raj
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs