1.) How badly would the lack of proper data alignment affect performance? Given the overhead involved with accessing "members" of the synthetic structures, is data-alignment even a significant contributing factor?
This is entirely dependent on the CPU architecture and compiler. On some systems you may just have a performance penalty, but on others you could get a crash.
2.) Is there a better way of doing this given the constraints of run-time synthesis?
Here's an example of how you might create a properly aligned synthesized struct at runtime:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char junk1;
char junk2;
} A;
typedef struct {
int junk3;
int junk4;
} B;
typedef struct {
double junk5;
char junk6;
} C;
static size_t roundUp(size_t value,size_t factor)
{
return value+factor-1-((value+factor-1)%factor);
}
#define alignof(type) (sizeof(struct {type a;char b;})-sizeof(type))
int main(int argc,char **argv)
{
size_t offsets[3];
size_t pos = 0;
pos = roundUp(pos,alignof(A));
offsets[0] = pos;
pos += sizeof(A);
pos = roundUp(pos,alignof(B));
offsets[1] = pos;
pos += sizeof(B);
pos = roundUp(pos,alignof(C));
offsets[2] = pos;
pos += sizeof(C);
{
char *foobar = malloc(pos);
A *a = (A *)(foobar + offsets[0]);
B *b = (B *)(foobar + offsets[1]);
C *c = (C *)(foobar + offsets[2]);
a->junk1 = 1;
a->junk2 = 2;
b->junk3 = 3;
b->junk4 = 4;
c->junk5 = 5;
c->junk6 = 6;
free(foobar);
}
return 0;
}
The alignment of a particular struct is determined by creating a struct with the original struct and an extra char. The compiler will automatically add enough padding to make sure that the necessary alignment is preserved if you were to use an array of these structs, so by measuring the difference in sizes, we get the proper alignment.
Using the alignment information, we can create a table of where each member of the synthesized struct should live relative to the beginning. We just have to make sure that the position of each member has the proper alignment by rounding the position up to the nearest multiple of the alignment.
You should be able to generalize this to any number of members.
Note that if you wanted to determine the overall size if your synthesized struct (what sizeof() might return), so that you could create an array of these synthesized structs, then you need to get the combined alignment requirement and roundUp the final pos to that factor. The combined alignment will be the least common multiple of the individual alignments.