Version française
Home     About     Download     Resources     Contact us    
Browse thread
Safe Obj.magic container ?
[ 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: [Caml-list] Safe Obj.magic container ?
On 2008-02-27, at 10:43, Luc Maranget wrote:

> The semantics of Obj.magic is as follows:
>
> 1. Obj.magic does not exist. Don't use it.
>
> 2. Obj.magic is black magic, you can see it as the identity
>  (fun x -> x)  with type 'a -> 'b.
>
> As I see it, 2. steems from the uniform representation of values by  
> OCaml.
>
> A value is either a scalar, or a pointer, and this can be tested
> dynamically (by looking at the low order bit) by
> Obj.is_int/Obj.is_block.


If that was the whole story, Obj.magic would be pretty safe.  But
there are exceptions to the uniform representation of values, and
they make Obj.magic really hard to use.

The most important exception is floating-point numbers.  They are
not always represented as one word each, and that means even
Obj.repr is unsafe.

Example (on a 32-bit machine):

        Objective Caml version 3.10.2+rc1

# let x = Obj.repr 1;;
val x : Obj.t = <abstr>
# let y = Obj.repr 1.0;;
val y : Obj.t = <abstr>
# [| x; y |];;
- : Obj.t array = [|<abstr>; <abstr>|]
# [| y; x |];;
Bus error

My advice: don't use the Obj module if you were surprised by this
example.

-- Damien