www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - casting between structs

reply "Mariusz `shd` =?UTF-8?B?R2xpd2nFhHNraSI=?= <alienballance gmail.com> writes:
I'd like to reinterpret data as different type without copying.

extern(C) struct A{ /* */ }
struct B
   A a;
   alias a this;

extern(C) A* f1(){ /* */ }

B* f2()
   return cast(B*) f1();

Assuming that i cast() correct state, i'd like to know if:
* it's currently safe
* it's guaranteed to be safe in the future
* there any precautions in using this pattern

Most important thing for me is a type-check, but defining 
operators ( since they can't be external ) would be nice too.

I'm asking because i'd like to use this pattern a lot in my code, 
and with my limited knowledge it's good to get some feedback of 
more experienced.

   In situations when i return by value instead of pointer - will 
memory copying be optimized away ?
Dec 18 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Mariusz `shd` GliwiƄski:

 * it's currently safe
One thing to remember when casting, is that when you cast const/immutable to mutable, then you can't mutate the data. Bye, bearophile
Dec 18 2013