Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Using C values in ocaml code
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-01-31 (15:05)
From: Tomasz Zielonka <zielony@c...>
Subject: Re: [Caml-list] Using C values in ocaml code
On Thu, Jan 31, 2002 at 12:12:51PM +0100, Markus Mottl wrote:

> You can't just cast 'x' to an OCaml-value: if it is an integer, you'll
> have to use the "Val_int"-macro. Otherwise the integer might exceed the
> range allowed by OCaml and could be interpreted as a pointer by the GC,
> possibly resulting in a crash (integers need to be tagged).

It's even more fun. Odd ints would be interpreted as ints with halved
value, even ints as pointers.

from mlvalues.h:

#define Is_long(x)   (((x) & 1) != 0)
#define Long_val(x)     ((x) >> 1)
#define Int_val(x) ((int) Long_val(x))

> If it is a pointer to something allocated by C, you could return it
> directly, but this may cause troubles if you deallocate this region of
> memory while the value is still reachable from the OCaml-world (read
> section 17.2.3 to learn what can happen).

Both - an integer or a pointer.  It is not always possible to check
whether it is a pointer or an integer not knowing the context. 

> Therefore you should use a more appropriate encoding. If you don't want
> the GC to notify your C-program that the value is not reachable from your
> program anymore (i.e. can be finalized/deallocated), then just allocate
> a block tagged abstract of size 1, e.g:

I will use abstract block then.


   .-.   Tomasz Zielonka                           CYBER SERVICE
   oo|   programista              
 (\_;/)  tel: [48] (22) 723-06-79 | tel/fax: [48] (22) 723-01-75
Bug reports:  FAQ:
To unsubscribe, mail  Archives: