I'm reading values from a (PE) binary file. The values have a known length and position in the file and are stored with no padding (right next to each other). They store various types (int, long, pointer, array...).
I'm trying to parse those binary structures and store them in a useful way. The obvious way to do it is to just:
struct IMAGE_FILE_HEADER {
WORD Machine;
WORD NumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORD SizeOfOptionalHeader;
WORD Characteristics;
};
However, this has the downside that, in writing the values to the struct, I have to manually write (using the assignment operator) every value one by one, which is time consuming and requires a bunch of boilerplate code (I have hundreds of these values). The upside is that it's type-safe. Doing a memcpy
is not feasible because of struct memory alignment issues.
Another option is to use an unordered map to store the key-value pairs, but this doesn't work because my binary data has values of various types. I could create a map for every type, but that just seems unnecessarily complicated.
Polymorphism is a third option. I could write a BaseValue
class and have each of the types inherit from BaseValue
. Then I could just store a map of BaseValue
types. This would work, but it's extremely hacky and not type-safe.
It seems like such a simple task. Just read a binary file with different types into a structure. How can I do this task in a way that doesn't require a bunch of boilerplate code and is type-safe? Thank you.
Edit:
The boilerplate would just consist of hundreds of lines like this one:
this.NumberOfSections = data.Read<WORD>(1234);
IMAGE_FILE_HEADER h {}; parser >> h.Machine >> h.NumberOfSections >> h.TimeDateStamp >> ...
wheretemplate<class T> Parser& operator>>(Parser&, T& target)