I have the following packet layout:
struct PacketLayout
{
int GateCode;
BYTE StringLen;
char String[StringLen];
BYTE ServerStatus;
BYTE ServerStorage;
BYTE ServerNumber;
}
The class is this:
class ServerInfo
{
short PacketSize; //Size of the whole packet
BYTE TotalServers; //total of PacketLayout structs
PacketLayout Server[TotalServers];
int GlobalSecCode;
short EncryptedPacketSize; //Same as the first member, just xored
}
So the problem i have is making an variable size array inside an class or an struct which size depends of the last member pointed by BYTE StringLen (for struct) and BYTE TotalServers (for the class).
I don’t know what is the solution to this, maybe implement a template?, if that’s so can i see an example (i am not familiar with templates yet) also i want to reference my member names without calculating the pointer position by myself (as i am currently doing now).
Thanks.
Doing this with a template is possible, for example:
lets you use this as:
Normally what you would want to do is simpler though. For example if you reorder the packet and know the upper limit on size you can do simply:
Or alternatively:
and allocate/set
Stringduring reading.Personally though I’d skip all this messy low level details and use something like protobuf to do the work for you and leave you free to concentrate on the more important higher level things that add value to your project.
There’s a common but dirty trick used sometimes too:
Where people define the size of the variable part at the end to be 1 and then deliberately allocate more memory than needed for the struct so they can write past the end of it. This is evil and very much not recommended though.