www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - casting issue

reply Alexandr Druzhinin <drug2004 bk.ru> writes:
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
next sibling parent "Dicebot" <public dicebot.lv> writes:
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.
Oct 24 2013
prev sibling parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
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
parent Alexandr Druzhinin <drug2004 bk.ru> writes:
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!
Oct 24 2013