digitalmars.D.learn - casting issue
- Alexandr Druzhinin (11/11) Oct 24 2013 May I cast like:
- Dicebot (7/18) Oct 24 2013 Not entirely. Try adding `align(64)` to struct declaration and
- Adam D. Ruppe (24/25) Oct 24 2013 Two options would be to make the points itself be a float[] with
- Alexandr Druzhinin (3/26) Oct 24 2013 I thought to use union, but using struct with properties is good to
May I cast like: struct Point { float x, y, z; float r, g, b, a; } Point[] points; void foo(float[] float_array) {}; foo(cast(float[]) points); // is it safe? May be more elegant way do express this exists? Thanks
Oct 24 2013
On Thursday, 24 October 2013 at 17:59:03 UTC, Alexandr Druzhinin wrote:May I cast like: struct Point { float x, y, z; float r, g, b, a; } Point[] points; void foo(float[] float_array) {}; foo(cast(float[]) points); // is it safe? May be more elegant way do express this exists? ThanksNot entirely. Try adding `align(64)` to struct declaration and observe funny change ;) It is clearly some low-level hack and not something for usage in normal code. One can create array from struct instance via [ point.tupleof ], but this will allocate as all array literals do.
Oct 24 2013
On Thursday, 24 October 2013 at 17:59:03 UTC, Alexandr Druzhinin wrote:foo(cast(float[]) points); // is it safe?Two options would be to make the points itself be a float[] with the names just properties into the index: struct Point { float[7] data; ref float x() { return data[0]; } ref float y() { return data[1]; } // etc etc etc } then to use it, just pass point.data[] instead of casting. Or you could also do a union: struct Point { union { float[7] data; struct { float x,y,z,r,g,b,a; } } } and again, pass point.data[] instead of casting it, while continuing to use the other members normally. These are both well defined so are less likely to break than the cast.
Oct 24 2013
25.10.2013 02:08, Adam D. Ruppe пишет:On Thursday, 24 October 2013 at 17:59:03 UTC, Alexandr Druzhinin wrote:I thought to use union, but using struct with properties is good to know. Thanks for sharing!foo(cast(float[]) points); // is it safe?Two options would be to make the points itself be a float[] with the names just properties into the index: struct Point { float[7] data; ref float x() { return data[0]; } ref float y() { return data[1]; } // etc etc etc } then to use it, just pass point.data[] instead of casting. Or you could also do a union: struct Point { union { float[7] data; struct { float x,y,z,r,g,b,a; } } } and again, pass point.data[] instead of casting it, while continuing to use the other members normally. These are both well defined so are less likely to break than the cast.
Oct 24 2013