Re: Casting between structs of the same size is treated as a bit cast?
On Wednesday, 20 October 2021 at 04:14:37 UTC, Dave P. wrote: I am confused on how casting structs works. According to point 9 of https://dlang.org/spec/expression.html#CastExpression: Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to: ```d S(v) ``` It says `value v` and `struct S`, but you go on to cast a struct into another struct. Point 9 is exhibited by ```d struct Foo { int i; } unittest { int n = 2; Foo f = cast(Foo) n; } ``` However, the following program compiles and the resulting execution indicates the bits are just being reinterpreted. ... Is this a bug in my understanding? Bug in the spec? Bug in the compiler? It looks at least like a gap in the spec. Adding "or a struct to another struct" to point six would fit the observed behavior.
Casting between structs of the same size is treated as a bit cast?
I am confused on how casting structs works. According to point 9 of https://dlang.org/spec/expression.html#CastExpression: Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to: ```d S(v) ``` However, the following program compiles and the resulting execution indicates the bits are just being reinterpreted. ```d // casttest.d import std; struct Foo { int i; float x; } struct Bar { float i; int x; } void main(){ Foo foo = Foo(10, 1.035); writeln(foo); auto b = cast(Bar)foo; writeln(b); auto c = cast(Bar)b; writeln(c); // auto d = Bar(foo); // casttest.d(21): Error: cannot implicitly convert expression `foo` of type `Foo` to `float` // auto e = Bar(b); // casttest.d(22): Error: cannot implicitly convert expression `b` of type `Bar` to `float` } ``` Execution results in: ``` Foo(10, 1.035) Bar(1.4013e-44, 1065646817) Bar(1.4013e-44, 1065646817) ``` Additionally, the commented out lines indicate that what the spec claims the cast is equivalent to wouldn’t even work. Is this a bug in my understanding? Bug in the spec? Bug in the compiler?
casting between structs
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. Ps. In situations when i return by value instead of pointer - will memory copying be optimized away ?
Re: casting between structs
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