How to dynamically alias a struct to a byte array?

Charles Hixson charleshixsn at earthlink.net
Tue Feb 19 16:38:05 PST 2013


On 02/17/2013 09:32 PM, Ali Çehreli wrote:
> On 02/17/2013 12:12 PM, jerro wrote:
>
>  > You don't need to cast it each time, you can do something like:
>  >
>  > auto structPointer = cast(MyStruct*) byteArray.ptr;
>
> And that pointer can be converted to a D slice:
>
> MyStruct[] slice = structPointer[0..number_of_struct_objects];
>
> Use 'slice' as a regular D slice from that point on.
>
> Ali
>

Unfortunately, it's a struct because it isn't an array.  It's several 
arrays, not all of the same type.  (one int array, one uint array, one 
long array, a few counters and flags, and occasionally also a char array 
[actually a utf-8 string], but since it's coming in from C it doesn't 
start out as immutable, and it contains an extra terminal \0.)  So a 
slice wouldn't work.

The structPointer would work, but since I really dislike working with 
pointers, I'll probably convert it into a class with dynamic arrays 
almost immediately.  And on the way out, convert it back into a byte 
array at the very last moment.  This will be a bit less efficient, but 
as a trade-off, I won't get confused about what I'm doing (or not as 
much so).
(OTOH, do note that the structPointer approach would require that I 
define lots of different structs, whereas if I convert it into a class, 
I can get by with one definition, and a more complicated construct/emit 
pair.  So it's probably a reasonable tradeoff...or perhaps even a bit 
favorable towards the class, even though every reference to a dynamic 
array involves an extra dereference.)


More information about the Digitalmars-d-learn mailing list