Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] about Obj.magic
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Warp <warplayer@f...>
Subject: Re: [Caml-list] about Obj.magic
> When should I use 'Obj.magic'? It is really confusing. Now I am converting
> a bunch of code from sml to ocaml. During the process, I want to make
> sure that the type of every function keep consistent with the original
> one. But I still encountered a lot of problems about the types in ocaml.
> For examples, all my base functions are fine in ocaml. But, sometimes when
> I tried to combine a few base functions together in the same way as my
> original code, I got a type error. After endless trial, I have to use
> 'Obj.magic'. In some sense, it is good because I can compile my code
> now. On the other hand, things will be worse because it is very difficult
> to debug if I use a few 'Obj.magic' in my code. I couldn't find out the
> origins of all the runtime errors.
>
> So, we should be very careful to use 'Obj.magic'. Can somebody tell me
> the appropriate situation to use this function?

One case can be 'almost-legal' : downcasting an object to its implementation
class if you're sure that it has been previously upcasted to the interface
type class.

ex :

(* MLI file *)

class type intf =
  sig
    method a : unit
  end

val new_intf : intf -> intf

(* ML file *)

class impl parent =
  object
    method a = ....
    method b = ....
  end

let new_intf i = (new impl (Obj.magic i : impl) :> intf) (* upcast impl to
intf in order to hide method 'b' *)

Nicolas Cannasse
www.motion-twin.com


-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners