Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Using %identity for casting types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Using %identity for casting types
From: Jérôme Marant <marant.logatique@fr.thalesgroup.com>
>
>   I'm doing some experiments in interfacing OCaml with C++ and
>   it is sometimes necessary to cast one type to another.
>   I've seen in lablgtk something like:
>     external unsafe_cast : 'a obj -> 'b obj = "%identity"
> 
>   It is meant to be used by the end user?

Well, not really, but if you're interfacing with C++, it's not more
dangerous to do the cast in ocaml than in C++ (except if you use
rtti).

The above idiom is equivalent to

    let unsafe_cast : 'a obj -> 'b obj = Obj.magic

It may be more efficient, as the compiler knows that unsafe_cast is
the identity, and can discard it. No code is generated.

I also tend to prefer it because it makes clear the need to properly
write types: such casts only make sense at a precise type, while
Obj.magic is 'a -> 'b, which allows too much.

And, as always, only use unsafe casts for non-ocaml data.
Ocaml datatypes are expressive enough that you don't need unsafe
casts for them.

Jacques Garrigue-------------------
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