gpt4 book ai didi

c++ - 将对象转换为 char,然后转换为 "uncasting it back"

转载 作者:行者123 更新时间:2023-11-28 00:53:23 25 4
gpt4 key购买 nike

如果你有对象

struct Packet P;

组成
struct Packet {
struct Packet_header header;
unsigned char data[MAXIMUM_BUFFER_LENGTH];
};

标题由

组成
struct Packet_header {
unsigned int checksum;
unsigned int seq;
unsigned int ack;
unsigned int data_length;
};

如果我尝试抛出数据包

(unsigned char*) &P

有没有办法让我“uncast”回去得到我原来的数据包 P?

最佳答案

最简单的方法是使用 reinterpret_cast<Packet>(*(reinterpret_cast<Packet*>(pUC))) , 其中pUCunsigned char* .

正确的方法是在Packet_header ,一个转换构造函数和一个转换运算符(或类似转换的方法):

struct Packet_header {
Packet_header(unsigned char*); //construct object form unsigned char*
operator unsigned char*(); //cast it back
const unsigned char* getUC(); //or get an unsigned char*

unsigned int checksum;
unsigned int seq;
unsigned int ack;
unsigned int data_length;
};

关于c++ - 将对象转换为 char,然后转换为 "uncasting it back",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com