Converting UNALIGNED MSVC specific code to portable C++ code?

Viewed 547

I'm trying to convert some C++ Code that is written for MSVC so it can run on GCC or Clang.

The offending keyword is

UNALIGNED

pData is LPCBYTE

An example of the code is:

 INT8 some8Value =  *(UNALIGNED INT8 *)&(pData[offset]);

INT64 some64Value = *(UNALIGNED INT64 *)&(pData[offset]);

I think I understand what logically this code wants to do, it wants to read in the 1 byte from the pointer pointing to pData + offset.

The second one is saying read 8 bytes from the pData + offset pointer.

The confusing part is why is the first one UNALIGNED. I thought reading 1 byte is always aligned.

Or am I misreading the code somehow?

Is the cross platform way of doing this the following:

INT8 part1 = pData[offset];
INT8 part2 = pData[offset + 1];
...

And then combine the 8 parts (for example) in the INT64 case?

2 Answers

In GCC you can use aligned(1) attribute:

typedef int64_t __attribute__(( aligned(1) )) UNALIGNED_INT64;

UNALIGNED_INT64 unalignedPtr = pData + offset;
INT64 some64Value = *unalignedPtr;

from the GCC documentation:

When used on a struct, or struct member, the aligned attribute can only increase the alignment; in order to decrease it, the packed attribute must be specified as well. When used as part of a typedef, the aligned attribute can both increase and decrease alignment, and specifying the packed attribute generates a warning.

Read more here: Why does this alignment attribute have to be specified in a typedef?

Related