Originally Posted by
dwks
That's right -- "the compiler is responsible for padding". So any code you write that assumes something like this will be unportable, reliant on compiler settings. Sure, on practically any compiler you can set this sort of thing, but it's an extra step involved. Your code doesn't compile out of the box on a new compiler.
But there should also be a way to force padding by a pragma. Though I'm not sure such a pragma exists on all compilers, or even if it's part of the standard.
But then again, many project modify compiler options and requires them to be changed to compile so setting padding in those projects isn't that much of a problem, but I do agree that it isn't usual practice and might be avoided.
Here is an example:
Code:
struct KeyStruct
{
bool bKeyStart;
bool bKeySelect;
bool bKeyDoSomething1;
bool bKeyDoSomething2;
};
int main() // Some function in your app calls the library
{
KeyStruct Keys;
// Register all your keys here...
GetKeys(&Keys, 4); // Also pass along how many keys you would have registered in this example
// Do something with your new information
}
void GetKeys(BYTE* pStruct, int keys)
{
// Get data somehow
bool bSet = true, bCleared = false;
/* If key 1 was pressed */ memcpy(pStruct, &bSet, 1); else memcpy(pStruct, &bCleared, 1);
/* If key 2 was pressed */ memcpy(pStruct + 1, &bSet, 1); else memcpy(pStruct + 1, &bCleared, 1);
/* If key 3 was pressed */ memcpy(pStruct + 2, &bSet, 1); else memcpy(pStruct + 2, &bCleared, 1);
/* If key 4 was pressed */ memcpy(pStruct + 3, &bSet, 1); else memcpy(pStruct + 3, &bCleared, 1);
}
And there you go, showing how appropriate it sometimes can be. Of course it's also possible to declare a struct with one bool array, it's just a matter of preferance.
But your other solution - to pass a struct and then copy it would be a waste of memory and time IMO, since I don't like copying memory when possible. Also, passing a predefined struct, you'd have to have a dynamically created array in it since the amount of keys can vary.
So either we use a pointer and new or we could use a class like CArray or something.