The project I'm working on has a need to represent many different hardware registers to our users as class objects. I'm nearly done on my object model, but I'm at one hurdle that I'm not sure how to surpass yet. These registers are exposed using structures. All of these register structures will inherit from a base struct which will provide useful things like how to get the particular register value from memory and store it to the bit field.
Now, the nice thing is that all of these registers are nicely aligned DWORDs. So, my code is something like this:
struct Base {
DWORD offset;
Driver* pToDrv;
// methods to set/get values to the registers using the driver pointer
void SetRegister(DWORD val);
};
struct Register1 : public Base {
DWORD bit0 : 1;
DWORD bit1 : 1;
// etc. until 32 bits
DWORD bit31 : 1;
// getters/setters for the individual bits
void SetFullRegister(DWORD val) {
*(reinterpret_cast<DWORD*>(this)) = val; // uh-oh! This doesn't point to bitfield
SetRegister(reinterpret_cast<DWORD*>(this)); // same thing here
}
};
I've verified with a simpler approach in a smaller program that this points to the Base instance even when used in the derived object's methods. How do I ensure that this points to the start of the derived object for the operations I'm trying to do?
I've tried the following approach:
*(reinterpret_cast<DWORD*>(this + sizeof(Derv))) = val;
Although nothing bad seemingly happened, the net result was that nothing at all happened. I know this isn't true because the value was assigned somewhere but, cringe, I've no idea where. This obviously isn't working nor is it a safe approach.
Please let me know if I've not adequately described my problem.
Thanks, Andy