将char数组强制转换为struct *类型 [英] Casting a char array to be of type struct *

查看:142
本文介绍了将char数组强制转换为struct *类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,也许有人可以解释struct ether_header *eh = (struct ether_header *) sendbuf;行上发生了什么?我了解它正在创建类型为ether_header的指针eh,并且在RHS上,您正在将sendbuf强制转换为tyoe struct ether_header的指针.但是,如果sendbufchar array,该怎么办?还有你为什么要这样做呢?

In the code below could somebody perhaps explain what is happening on the line struct ether_header *eh = (struct ether_header *) sendbuf;? I understand that it is creating a pointer eh of type ether_header and on the RHS you are casting sendbuf to be a pointer of tyoe struct ether_header. But how can you do this is sendbuf is a char array? Also why would you do this?

此处是完整代码的链接发送以太网帧

Here is the link to the full code send ethernet frame

#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>

int main(int argc, char *argv[])
{
    int sockfd;
    struct ifreq if_idx;
    struct ifreq if_mac;
    int tx_len = 0;
    char sendbuf[BUF_SIZ];
    struct ether_header *eh = (struct ether_header *) sendbuf;

推荐答案

但是,如果sendbufchar数组,那么如何执行 is ?

But how can you do this isif sendbuf is a char array?

代码不应该这样做.

将指针投射到最初不是该类型的有效指针的类型是未定义行为(UB).

Casting a pointer to a type that was not originally a valid pointer for that type is undefined behavior (UB).

char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf;  // UB

至少要考虑struct ether_header是否具有对齐要求,以使其为偶数地址,而sendbuf[]是否以奇数地址开始.作业可能会终止程序.

At a minimum, consider if struct ether_header had an alignment requirement to be an even address and sendbuf[] began on an odd address. The assignment may kill the program.

第二个问题是未发布的代码以后可能会使用sendbuf[]eh做什么,这会违反严格的别名规则

A 2nd concern is what unposted code might later do with sendbuf[] and eh which can violating strict aliasing rule @Andrew Henle.

更好的方法是使用union.现在,成员已对齐,并且union处理严格的别名规则.

A better approach is to use a union. Now the members are aligned and the union handles the strict aliasing rule.

union {
  char sendbuf[BUF_SIZ];
  struct ether_header eh;
} u;


您为什么还要这么做?

Also why would you do this?

允许从2个数据类型的角度访问数据.也许要进行u的数据转储.

To allow access to the data from 2 data type perspectives. Perhaps to make a data dump of u.

这篇关于将char数组强制转换为struct *类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆