Thread overview | ||||||
---|---|---|---|---|---|---|
|
October 24, 2013 casting issue | ||||
---|---|---|---|---|
| ||||
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 |
October 24, 2013 Re: casting issue | ||||
---|---|---|---|---|
| ||||
Posted in reply to Alexandr Druzhinin | 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?
>
> Thanks
Not 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.
|
October 24, 2013 Re: casting issue | ||||
---|---|---|---|---|
| ||||
Posted in reply to Alexandr Druzhinin | 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.
|
October 24, 2013 Re: casting issue | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | 25.10.2013 02:08, Adam D. Ruppe пишет:
> 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.
I thought to use union, but using struct with properties is good to know. Thanks for sharing!
|
Copyright © 1999-2021 by the D Language Foundation