vendredi 5 juin 2020

I want to memcpy directly into a struct, but none of the methods are avoiding the padding issue correctly

I'm trying to open a binary file and read the Header from it. I'm able to read it in a series of integers, but I decided to convert it into a struct to allow for n-number of objects. However, I'm facing different issues each time, and they're all about the padding that structs introduce. When I tried

struct {
int x1;
int x2;
long long x3;
long long x4;
} info;

I ran into an issue where x1 and x2 are followed by a padding of size 4.

When I tried

struct {
uint32 x1;
uint32 x2;
uint64 x3;
uint64 x4;
} info;

I ran into an issue where the sizeof(info) is returning a size greatly larger than the first struct. I wanted to try pragma pack but I want a universal Windows solution that doesn't rely on Visual Studio. I know about ordering the declarations correctly to avoid the padding, but the problem is that the order is important, since I'm reading a binary file using memcpy(&info, bytes_array, sizeof(info)).

I would like to get advice on how to accomplish this properly, even if it meant that I have to change how my struct looks like.

My current code:

unsigned int read_size = sizeof(info);
char* read_array = new char [read_size];
fin.read(read_array, read_size);

memcpy(&info, read_array, read_size);

Aucun commentaire:

Enregistrer un commentaire