blah blah blah is here! blah blah » Close

up1down
link

I have the following:

struct _triggerSegment{
char cSegmentSource;
unsigned int uiSegmentTime;
unsigned int uiSegmentWidth;
unsigned int uiSegmentWindow;
};

struct _triggerEntry{
char cGuid[16];
char cName[32];
unsigned int uiResetTime;
char cSegmentCount;
struct _triggerSegment triggerSegment[5];
};


I calculate the size of _triggerEntry to be 118.

The compiler has determined it's 136. Why/how?

*note size_of unsigned int is 4.

-- EDIT --

I think this might be due to the compiler aligning on 32 bit boundaries. The single chars inside each are causing this. This adds 3 bytes to each and since there are 5 triggerSegments the total added for alignment is 3 * 6 = 18.

If this indeed is the case... any way to force the compiler to not align even if there is a performance hit?

last answered 5 months ago

1 answers

link

Yes, you're right that the compiler is aligning on 4 byte boundaries.

If you're using the Visual C/C++ compiler, you can temporarily change the alignment for structs using #pragma pack:

#pragma pack(push)  // push current alignment to stack
#pragma pack(1) // set packing alignment to 1 byte

struct _triggerSegment{
char cSegmentSource;
unsigned int uiSegmentTime;
unsigned int uiSegmentWidth;
unsigned int uiSegmentWindow;
};

struct _triggerEntry{
char cGuid[16];
char cName[32];
unsigned int uiResetTime;
char cSegmentCount;
struct _triggerSegment triggerSegment[5];
};

#pragma pack(pop) // pop original alignment from stack

foamy
1822

That is some seriously hairy stuff vulpes, even for you :D

vulpes
11603

Yep, don't get many questions on C these days :) In C#, all you need to do is to decorate your structs with [StructLayout(LayoutKind.Sequential, Pack=1)]. We have the #pragma directive but it's seldom used.

foamy
1822

Would there, in C#, be any performance gain to creating a struct like this rather than creating a class?

vulpes
11603

In this particular case, probably not. The first C struct is a reasonable candidate for a struct in C# (4 value type fields, 16 bytes storage including padding). However, the second C struct is not such a good candidate because of the three 'in line' arrays which C# can't do except when using unsafe code (it can't do the struct array even then!). You'd therefore have to use reference types for these array fields which is not great for a struct because the GC needs to track them.

Feedback