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
A pair of "Interfacing with C" questions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-07-21 (10:22)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] A pair of "Interfacing with C" questions
From: Robert Roessler <roessler@rftp.com>

> 1) in wrapping a large widget with multiple interfaces using 
> "strings", I sometimes allow the widget to copy a C-string into a 
> Caml-allocated string - INCLUDING "overwriting" the terminating zero 
> byte with zero... I wanted to make sure this was not seen as a major 
> problem.

No problem currently: for C compatibility all ocaml strings have a 0
after their end. Nobody can give "future" guarantees, but if there is
a change at this level, I assume this would be well publicised.

> 2) this is about "future-proofing" (at the source level) code which 
> interfaces with external [foreign] components and needs to store and 
> pass around "opaque pointers": what is the best base Caml data type to 
> use?
> I currently use
> type opaque_ptr = int32
> I assume the other choices include int64, nativeint, or even int.

If you look at mlvalues.h you will see that nativeint is define as
long int. So this should be the natural format for a pointer.

The other option is to use store them in an ocaml int, without any
conversion, as 4-byte aligned pointers outside of the heap are ignored
by the GC. But this has some pitfalls, as some dangling pointers may
end up pointing to a newly allocated heap area. This is also less
"future proof", as the representation of ocaml integers might change

Another advantage of nativeint is that they are custom block, so you
just have to change the allocation to make them GC-aware. This is why
I converted all pointers to custom-format blocks in lablgtk.

> nativeint - this looks promising, as long as you do not need to deal 
> with a 64-bit-int/32-bit-pointer model... would it be safe to assume 
> that in any 64-bit Caml implementation, ints/pointers/"values" will 
> ALL be 64-bit?

This is certainly currently the case, and without a radical change in
the approach to polymorphism, all "basic" ocaml types must have the
same size, and for practical reasons it is good that machine pointers
fit in this size. I suppose this does not exclude compiling ocaml in
32-bit mode on 64-bit machines that support such a mode, but even in this
case this supposes that (32-bit) pointers fit in an ocaml memory unit.

Jacques Garrigue