Difficulty copying multi dimensional static array to dynamic array.

Bill Baxter dnewsgroup at billbaxter.com
Mon Feb 25 16:23:37 PST 2008


Spacen Jasset wrote:
> Derek Parnell wrote:
>> On Tue, 26 Feb 2008 09:39:49 +1100, Derek Parnell wrote:
>>
>>> On Mon, 25 Feb 2008 23:11:11 +0100, Saaa wrote:
>>>
>>>> Using ref should do the trick without pointers.
>>
>> Oh and if it's "tricks" you want ;-) this works ...
>>
>> import std.stdio;
>> struct nastytrick(T)
>> {
>>     T m;
>> }
>>
>> alias float[3][5]       a2D;
>> alias nastytrick!(a2D) sa2D;
>>
>> void fillArray(ref sa2D data)
>> {
>>   invariant int maxi = data.m.length;
>>   invariant int maxj = data.m[0].length;
>>       for (int i = 0; i < maxi; i++)
>>       for (int j = 0; j < maxj; j++)
>>         data.m[i][j] = i*maxj + j;
>>   }
>> void main()
>> {
>>     sa2D x; // declare static array inside its struct wrapper.
>>     fillArray( x );
>>     std.stdio.writefln("%s", x.m);
>> }
>>
>> It seems very odd that a struct can be passed using 'ref' but a fixed
>> length array can't be.
> I don't see the mystery. Arrays are *always* passed by reference. You 
> can't use ref because can't change a ref to a static array (becuase it's 
> static?) so it doesn't actually make sense, you can [I think] with a 
> class object -- Chanage it's ref using "ref" keyword so that it points 
> to a new object) So that is all fine and makes sense as far as I can see.
> 
> My beef is returning static arrays which you can't do. You can return 
> dynamic ones only.
> 
> It makes this impossible:
> 
> glMatrixMultiply( mymatrix.toFloatArray16() );
> 
> Instead you have to do something like this:
> 
> float[4][4] temp;
> mymatrix.toFloatArray16ByRef( temp );
> glMatrixMultiply( temp );
> 
> Or
> 
> glMatrixMultiply( *temp.toFloatArrayPointer() );
> 
> toFloatArrayPointer is:
> 
> float[16] * toFloatArrayPointer()
> {
>     static float[16] matrix;
>     return &matrix;
> }
> 
> 
> ...and then you can use a wrapping structure and so on. But this isn't 
> 'right' is it? or is it? Can why can I not use something like:
> 
> glMatrixMultiply( mymatrix.toFloatArray16() );
> 
> where toFloatArray16 is:
> 
> float[4][4] toFloatArray()
> {
>     float[4][4]    a;
>     return a; // a is returned like a struct would be. (i.e. copied onto 
> the stack and copied off on return. (or usually optimsed via a pointer 
> on the stack to the callers object perhaps - whatever dmd currently does)
> }

You could just store your matrix in the order GL wants, and then do:

   glMultMatrixf( mymatrix.ptr );

Where .ptr returns a float* pointing to the first element.

That's going to be hella more efficient than passing around big 
16-element float arrays by value.

--bb


More information about the Digitalmars-d-learn mailing list