7
CptFox
185d

Oh god, structure alignement, why you do this... You might be interested if you do C/C++ but haven't tried passing structures as binary to other programs.

Just started working recently with a lib that's only a DLL and a header file that doesn't compile. So using python I was able to use the DLL and redefined all of the structures using ctypes, and the nice thing is: it works.

But I spent the whole afternoon debugging why the data in my structures was incoherent. After much cussing, I figured out that the DLL was compiled with 2 bytes packing...

Packing refers to how structures don't just have all the data placed next to each other in a buffer. Instead, the standard way a compiler will allocate memory for a structure is to ensure that for each field of the structure, the offset between the pointer to the structure and the one to the field in that structure is a multiple of either the size of the field, or the size of the processor's words. That means that typically, you'll find that in a structure containing a char and a long, allocated at pointer p, the double will be starting at p+4 instead of the p+1 you might assume.
With most compilers, on most architectures, you still have the option to force an other alignment for your structures. Well that was the case here, with a single pragma hidden in a sea of ifdefs... Man that took some time to debug...

Comments
  • 0
    There are CPU architectures where unaligned access simply will crash. On others, it's "just" decreased performance. That's why C is adding pad bytes.
  • 0
    Nice catch!! Memory packing is seriously a pain sometimes...
Your Job Suck?
Get a Better Job
Add Comment