简体   繁体   English

在 C++ 中访问结构的成员

[英]Accessing member of struct in C++

I'm trying to access some data member inside a binary file, using a struct definition.我正在尝试使用结构定义访问二进制文件中的某些数据成员。

Inside thi file, it should contain a struct member called fxID.在这个文件中,它应该包含一个名为 fxID 的结构成员。 In the following code, I'm trying to access fxID, but it's not working, it's returning an incorrect number.在下面的代码中,我试图访问 fxID,但它不起作用,它返回了一个错误的数字。 Even more strangely, if I change fxID to fxVersion, I get the same number, so it does appear that the printf is not picking up the correct data at all.更奇怪的是,如果我将 fxID 更改为 fxVersion,我会得到相同的数字,因此似乎 printf 根本没有获取正确的数据。

FILE *p;
struct myStruct x;
p=fopen("myfile.fxb","rb");

size_t n = fread(&x, sizeof(x), 1, p);
if (n != 1) {
    // Some error message
    //printf("%i", sizeof(x));
} else {
    printf("\n\nID:%d\n",  x.fxID);
}

Any idea why I can't access the data inside fxID?知道为什么我无法访问 fxID 中的数据吗? I'm getting strange results depending on what type I use in the printf statement.根据我在 printf 语句中使用的类型,我得到了奇怪的结果。 For instance, I get the number 1606416148 if I use printf("%d", x.fxID);例如,如果我使用 printf("%d", x.fxID); ,我会得到数字 1606416148; However, this is wrong, because I believe the fxID is 1447514692. Is this because of the endianness?但是,这是错误的,因为我认为 fxID 是 1447514692。这是因为字节序吗? I know the file is big endian and it mentions something about needing to convert it in the header file I linked to.我知道该文件是大端的,它提到了需要在我链接到的头文件中转换它的一些内容。

Could it be due to using Int?可能是由于使用了 Int 吗? or the wrong type perhaps?或者错误的类型?

Endianess must be corrected for sure if the one used in the file is different from the one used by the platform.如果文件中使用的字节序与平台使用的字节序不同,则必须更正字节序。 If the format is stored using big endian layout then, if you are working on x64, you will have to swap the bytes of each multi-byte field.如果格式使用大端布局存储,那么如果您在 x64 上工作,则必须交换每个多字节字段的字节。

But this is not enough to guarantee that the layout of your struct is the same of the one used in the file format as it could contain padding and alignment requirements, so in general if you want to deserialize binary data directly inside a struct you must take care of multiple things.但这不足以保证struct的布局与文件格式中使用的布局相同,因为它可能包含填充和对齐要求,因此一般来说,如果您想直接在struct内反序列化二进制数据,则必须采用照顾多件事情。

In any case if the obtained result is 16064 1 6148 and you were expecting 1447514692 then endianness is not the only problem since both in hex are respectively 0x5FBFF714 and 0x56475244 which are not the same value with different endianness.在任何情况下,如果获得的结果是 16064 1 6148 并且您期望的是1447514692那么字节序不是唯一的问题,因为它们在十六进制中分别是0x5FBFF7140x56475244 ,它们不是具有不同字节序的相同值。

You are using &x.fxID which returns the address of the fxID field inside the struct, which is not the value, try to use x.fxID directy.您正在使用&x.fxID它返回结构内fxID字段的地址,这不是值,请尝试直接使用x.fxID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM