【问题标题】:Unable to understand the syntax of this statemnet "struct sll_header *shdr = (struct sll_header *)buf;"无法理解此 statemnet “struct sll_header *shdr = (struct sll_header *)buf;”的语法
【发布时间】:2024-01-15 13:26:01
【问题描述】:

下面是我试图通读的代码 sn-p。

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;
    }

【问题讨论】:

  • 看起来像 C 代码。可能是 C++,但它不是惯用的 C++。
  • 这只是一个类型转换。

标签: c pointers character structure


【解决方案1】:

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

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

没有类型大小写,你会得到一个编译器警告。

【讨论】: