首页 > 解决方案 > 无法理解此 statemnet “struct sll_header *shdr = (struct sll_header *)buf;”的语法

问题描述

下面是我试图通读的代码片段。

swap_linux_sll_header(const struct pcap_pkthdr *hdr, u_char *buf)
{
    u_int caplen = hdr->caplen;
    u_int length = hdr->len;
    struct sll_header *shdr = (struct sll_header *)buf;
    uint16_t protocol;
    pcap_can_socketcan_hdr *chdr;

    if (caplen < (u_int) sizeof(struct sll_header) ||
        length < (u_int) sizeof(struct sll_header)) {
        /* Not enough data to have the protocol field */
        return;
    }

标签: cpointerscharacterstructure

解决方案


这是一个简单的类型转换。buf 最初作为指向 u_char 的指针传递给函数,但在函数内部,它需要作为指向 sll_header 结构的指针来使用和检查/操作。

当缓冲区作为原始字节序列获得时,这很常见,也许它是从介质或网络中读取的,然后它被传递给理解它所代表的底层结构(例如 IP 数据包)并理解它的函数。

如果没有类型大小写,您将收到编译器警告。


推荐阅读