How can I map bytes to a matrix of structures?
Steven Schveighoffer
schveiguy at yahoo.com
Fri Sep 9 09:21:31 PDT 2011
On Fri, 09 Sep 2011 11:43:04 -0400, Timon Gehr <timon.gehr at gmx.ch> wrote:
> On 09/09/2011 05:19 PM, teo wrote:
>> Here is an example of what I am after:
>>
>> struct DATA
>> {
>> ubyte D1;
>> ubyte D2;
>> ubyte D3;
>> ubyte D4;
>> }
>>
>> void main()
>> {
>> ubyte[16] a = [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01,
>> 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 ];
>> auto b = (cast(DATA*)a.ptr)[0 .. 4];
>> auto c = (cast(DATA[]*)b.ptr)[0 .. 2][0 .. 2];
>> }
>>
>> I need to have a DATA[2][2]. That code compiles but gives me a
>> segmentation fault.
>
> If you actually want a dynamic DATA[2][] array of length 2, this works:
> auto b=(*(cast(DATA[2][2]*)a.ptr))[];
>
> Otherwise:
>
> A simple reinterpret cast should do:
> auto b=*(cast(DATA[2][2]*)a.ptr);
>
> but note that this copies the data, because static arrays have value
> semantics.
>
> If you want to have refer the new array to the same location, you can
> use a union.
>
> void main(){
> union Myunion{
> ubyte[16] a = [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01,
> 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 ];
> DATA[2][2] b;
> }
> Myunion myunion;
> assert(*(cast(DATA[2][2]*)myunion.a.ptr)==myunion.b);
> }
You can also use ref, but you have to use a function, as it's impossible
to declare a ref local variable except as a function parameter.
void main()
{
ubyte[16] a = ...;
void foo(ref DATA[2][2] b)
{
...
}
foo(*(cast(DATA[2][2]*)a.ptr));
}
-Steve
More information about the Digitalmars-d-learn
mailing list