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 (11:12)
From: Markus Mottl <markus@o...>
Subject: Re: [Caml-list] Using C values in ocaml code
On Thu, 31 Jan 2002, Tomasz Zielonka wrote:
>   value
>   get_some_value(value unit)
>   {
>     CAMLparam1(unit);
>     Datum x;
>     x = foo();
>     CAMLreturn((value) x)
>   }

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).

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).

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:

  value v = alloc_small(1, Abstract_tag);

and write your pointer into its (only) field using the Field-macro:

  Field(v, 0) = foo();

The above works with integers (no need for conversions then), too, btw.

If you want to have a function for finalization/deallocation called by
the GC but don't want to handle custom blocks in their full generality,
just use "alloc_final". It allows you to pass a finalization function
+ some GC-parameters and creates a custom block with the other custom
functions (hashing, etc.), set to default values.

See the manual for details...

Markus Mottl

Markus Mottl                                   
Austrian Research Institute
for Artificial Intelligence        
Bug reports:  FAQ:
To unsubscribe, mail  Archives: