Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: Is this use of Object.magic safe?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Damien Doligez <Damien.Doligez@i...>
Subject: Re: Is this use of Object.magic safe?
>From: Stephan Houben <stephan@pcrm.win.tue.nl>
>
>let value_of_int (i : int) : value =
>  Obj.magic i
>
>let value_of_allocated_value (av :allocated_value) : value=
>  Obj.magic av
> 
>let unwrap (int_func : int -> 'a) 
>                (aval_func : allocated_value -> 'a)
>                (v : value) : 'a =
>  if Obj.is_int (Obj.repr v)
>  then int_func (Obj.magic v)
>  else aval_func (Obj.magic v) 

>1. Is this safe w.r.t. the garbage collector? Or am I going to confuse the GC?

No problem with the GC.


>2. Can I safely marshall values?

No problem with marshalling either.


>3. Is it worth the trouble? Perhaps O'Caml already does something smart
>   when a constructor of the form `Int of int' is encountered?

It doesn't work as you expect because O'Caml is strongly typed, so it
can (and does) use a smart representation for your constant
constructors True and False  They are represented as integers, so your
unwrap function cannot tell the difference between a boolean and an
integer.  This is typical of the dangers of using Obj.magic.

-- Damien