Safe use of unsafeCoerce?

Simon Marlow simonmar at microsoft.com
Mon Apr 26 16:49:12 EDT 2004


On 24 April 2004 17:38, Duncan Coutts wrote:

> All,
> 
> I'm after advice on whether the following example is a safe use of
> unsafeCoerce, and if it is safe, if it's worth it.
> 
> In summary, if the following is ok:
> 
> castFooToBar :: Ptr Foo -> Ptr Bar
> castFooToBar = castPtr
> 
> then is the following ok?
> 
> newtype Foo' = Foo' (Ptr Foo)
> newtype Bar' = Bar' (Ptr Bar)
> 
> castFooToBar' :: Foo' -> Bar'
> castFooToBar' = unsafeCoerce

If the runtime representation of Foo' and Bar' is the same, then this is
safe.  In this case the runtime representation is the same, so you're
ok.

However, it might not always be a good idea, because the compiler's
optimiser gets a bit stuck when it sees an unsafeCoerce.  I'd like to be
a bit more specific, but I'm not sure I can remember the specific
example.  On the other hand, Happy makes extensive use of unsafeCoerce
in its generated code (when you use -c), so in some cases the benefits
can definitely outweigh the costs.

> Here's the context/motivation:
[ snip ]
> toGObject   :: GObjectClass o => o -> GObject
> toGObject = unsafeCoerce
> 
> fromGObject :: GObjectClass o => GObject -> o
> fromGObject = unsafeCoerce
> 
> So, the point is we can remove entirely the class dictionary that
> otherwise has to be carried round for every object and the upcasting &
> downcasting functions no longer need to do slow dictionary lookups
> when all they are really doing is casting C pointers.
> 
> So is it a) safe? b) kosher?

I think so.

On the other hand, you might want to look at using the trick that
wxHaskell uses for encoding the widget hierarchy, which also has zero
runtime cost.

Cheers,
	Simon


More information about the Glasgow-haskell-users mailing list