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
safe casting
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-08-22 (22:20)
From: David Allsopp <dra-news@m...>
Subject: RE: [Caml-list] safe casting
> Given two record types that are identical but in name, is it safe (if
> perhaps a poor idea) to cast between functions that are parametric in
> these record types:

Yes, it's safe because the representations of the data are the same -
Obj.magic essentially removes all the protection of the type system by
giving you an 'a -> 'b function. And, yes, it's a bad idea unless you have a
*really* good reason to do it and a lot of time to comment your code ;o)


> Put another way: is the implementation of two records w/ identical labels
> the same, or is there a runtime significance to their static difference?

The labels of a record are only of concern to the type checker - they are
discarded at runtime. Two records will have the same runtime representation
iff the types of each member (reading left -> right) are the same.

e.g. type t = {a : int; b : int}
and  type u = {c : int; d : int}

are the same at runtime. I *think* you can also get away with:

type t = {a : int; b : int}
type u = {c : int; d : int; e : int}

(Obj.magic {c = 3; d = 4; e = 5} : t)

i.e. a "downcast" of a variable of type u to one of type t: but I'm not sure
that would "work" in all contexts (especially where copying may be

However, it's all terribly bad programming practice in O'Caml because you
end up with code that is totally resistant to change and that relies on the
Obj module (which is not officially supported). Chapter 18 (Interfacing with
C) of the manual helps with understanding the underlying representations of
values at runtime.