简体   繁体   English

将 char[] 转换为 C++ 中的结构时,计算机会忽略一个字节

[英]A byte is ignored by the computer when casting a char[] to a struct in C++

I'm writing a client-server program where the client-side is written in C++ and the server-side is in Python.我正在编写一个客户端-服务器程序,其中客户端使用 C++ 编写,服务器端使用 Python。

A stream of bytes is sent from the server-side and received to a char[] buffer and then converted with reinterpret_cast to an appropriate struct.一个字节的 stream 从服务器端发送并接收到char[]缓冲区,然后使用reinterpret_cast转换为适当的结构。

char response_buffer[7];
recv(sock, response_buffer, 7, 0);
s_response* response = reinterpret_cast<s_response*>(response_buffer);
cout << response -> code << endl;

where the struct is defined this way:结构是这样定义的:

typedef struct {
    unsigned char version;
    unsigned short code;
    unsigned int payload_size;
} s_response;

But instead of version ( 1 byte ) getting the value in response_buffer[0] , and code getting response_buffer[1] and response_buffer[2] ( two bytes ), code ends up getting the value in response_buffer[2] and response_buffer[3] , and payload_size getting response_buffer[4] to response_buffer[6] , and thus, the value response_buffer[1] is not inserted into any of the struct's attributes and the result is a whole mess.但不是version1 字节)获得response_buffer[0]中的值, code获得response_buffer[1]response_buffer[2]两个字节), code最终获得response_buffer[2]response_buffer[3]中的值,而payload_sizeresponse_buffer[4]变为response_buffer[6] ,因此,值response_buffer[1]没有插入到任何结构的属性中,结果是一团糟。

At first, I thought that it's due to endianness, but when I send the values 2 , 2001 , and 13821 , for example, from the server-side, the following values are in response_buffer :起初,我认为这是由于字节顺序,但是当我从服务器端发送值2200113821时,以下值在response_buffer中:

0. 00000010
1. 11101001
2. 00000011
3. 11111101
4. 00110101
5. 00000000
6. 00000000

This is what I expect to get and in the right order.我期望得到的,并且顺序正确。 But when I print out response->code I get the value 64771 which is 11111101 00000011 (2 and 3 in the above list) instead of 2001 which is 00000011 11101001 (1 and 2 in the list).但是当我打印出response->code时,我得到的值是64771 ,即11111101 00000011 (上面列表中的 2 和 3),而不是2001 ,即00000011 11101001 (列表中的 1 和 2)。 Meaning, when I'm casting the char* to the s_response* , the byte in position 1 in the response_buffer is just ignored, and the values from there-on are one-byte shifted from the correct order.意思是,当我将char*转换为s_response*时, response_buffer中 position 1 中的字节将被忽略,并且从那里开始的值从正确的顺序偏移了一个字节。

Any idea what am I doing wrong?知道我在做什么错吗?

As written in the comments, it was struct padding that made the problem.正如评论中所写,是结构填充造成了问题。 It can be solved by adding #pragma s as shown below可以通过添加#pragma来解决,如下图

#pragma pack(push,1)
typedef struct {
    unsigned char version;
    unsigned short code;
    unsigned int payload_size;
} s_response;
#pragma pack(pop)

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

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