简体   繁体   English

将字符缓冲区类型转换为来自套接字的结构

[英]Typecasting a character buffer to a struct coming from a socket

I am using the following code to read data from a socket: 我正在使用以下代码从套接字读取数据:

while (true) 
{

        int len = 0;
        ioctl(sd, FIONREAD, &len);
        if (len > 0)
        {
                len = read(sd, databuf, len);                   
        }

        else
                std::cout << "error" << std::endl;
}

There is a stream of structures that is coming from the socket. 套接字有大量的结构。 the sizes of the structs is defined an I have them. 结构的大小是我定义的。

So how can I read a struct like : 所以我怎么能读一个像这样的结构:

 typedef struct
 {
      short msglen;
      short id;
      int seqno;
 }HEADER;

I thought of typecasting it, but I cannot figure out how to do it. 我曾想过要进行类型转换,但是我不知道该怎么做。 The character buffer will contain multiple structs one after the other. 字符缓冲区将一个接一个地包含多个结构。 I need to read just the first 8 bytes to get the first. 我只需要读取前8个字节即可获取第一个字节。

Also, there is a while loop because I am receiving a continuous stream of multicast messages from the network. 另外,还有一个while循环,因为我正在从网络接收连续的多播消息流。

std::memcpy(&header, buffer, sizeof(header));

The standard compliant and safe way is to use memcpy : 符合标准且安全的方法是使用memcpy

HEADER header;
char buffer[/*size*/]; 

/* read data into buffer */

std::memcpy(&header, buffer, sizeof(header));

Modern compilers are fully capable of optimizing away the function call. 现代编译器完全有能力优化掉函数调用。

Do not try casting buffer with something like reinterpret_cast . 不要尝试使用reinterpret_cast类的内容来转换buffer That's undefined behavior because it violates the strict aliasing rules (you can access the stored value of an object of any type through a glvalue of char or unsigned char type, but the reverse doesn't hold). 这是未定义的行为,因为它违反了严格的别名规则(您可以通过char的glvalue或unsigned char类型访问任何类型的对象的存储值,但相反情况并不成立)。

As a side note, typedef struct { /* ... */ } HEADER; 另外,请输入typedef struct { /* ... */ } HEADER; is a C-ism. 是一个C主义。 Just do struct HEADER { /* ... */ }; 只需执行struct HEADER { /* ... */ }; .

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

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