Dynamically Sized Structs
Justin Whear
justin at economicmodeling.com
Wed Apr 16 16:33:34 PDT 2014
On Wed, 16 Apr 2014 23:15:40 +0000, Jeroen Bollen wrote:
> Is it possible to have a structure with a dynamic size? The structure
> would contain an array.
>
> I know I can use templates, but the size won't be known at compile time.
> I also know I could just put a dynamic array into it, but that way it
> would just be a pointer.
>
> I know there would be major issues like how to pass the struct to a
> function, as it has an unknown size, but to be quite honest I just want
> pretty code. I'm doing network related operations. I was hoping there'd
> still be a way to do this using templates or so? I just don't want to go
> through the hassle of writing a constructor for it to fill in all the
> fields, and a toByteArray method to convert it back to raw data.
>
> struct MyStruct {
> ulong length;
> ubyte[length] data; // obv won't compile
> }
No, you can't make the structs dynamic. I had a similar situation
reading shapefiles a while ago and approached it like this:
struct lengthOf
{
string fieldName;
}
struct Polygon
{
ulong numParts;
@lengthOf("numParts") Part[] parts;
ulong numPoints;
@lengthOf("numPoints") Point[] points;
}
T read(T)(...)
if (/** T is one of your wire-format structs **/)
{
T ret;
foreach (I, field; ret.tupleof)
{
static if (isDynamicArray!(typeof(field)))
{
// use __traits(getAttributes) on the field to get the
lengthOf attribute
// mixin a line like this:
mixin(`field.length = ret.`~lengthOf.fieldName~`;`);
rawRead(field);
} else {
// Assume the field is a primitive and read it
}
}
return ret;
}
Can't find the actual code at the moment, but that's the gist of it.
More information about the Digitalmars-d-learn
mailing list