How to dynamically alias a struct to a byte array?

jerro a at a.com
Sun Feb 17 12:12:57 PST 2013


> The only thing I've though of so far is to declare a class that 
> holds a bunch of abstract methods, and then have multiple 
> descendants that each have a special variant of the struct.  
> And even then I've either got to copy it again, or to cast it 
> each time I use it.  (Though at least with this approach all 
> the casts are located in one area of the code.)

You don't need to cast it each time, you can do something like:

auto structPointer = cast(MyStruct*) byteArray.ptr;

and use structPointer after that (in D structPointer.foo will get 
the member foo, same as (*structPointer).foo). So if you go with 
the common parent approach , you can just store that pointer as a 
field. This will require one extra pointer dereference each time 
you access the struct, though. If you need to access it a lot it 
may be more efficient to make a field of type MyStrtuct and just 
copy the data to it. The time it takes to copy the struct 
shouldn't really be significant anyway, since you are reading it 
from a file and file IO is typically much slower than copying 
memory.

By the way, if you use the common parent approach, the common 
parent should probably be an interface 
(http://dlang.org/interface.html), not a class.


More information about the Digitalmars-d-learn mailing list