如何在 C++ 中将结构映射到字符正确的方法 [英] How to map structure to char proper method in C++

查看:63
本文介绍了如何在 C++ 中将结构映射到字符正确的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,我习惯于使用 char* 来映射一些表示网络数据包的结构.然后我只需分配数据包参数并通过网络发送:

In C I was used to work with char* to which I mapped some structure representing a network packet. Then I would just assign the packet parameters and send via network:

UPDATED - 我忘记补充一点,我有一些有效载荷

UPDATED - I forget to add that I have some payload

struct packet {
   uint64_t id __attribute__((packed)); 
   uint64_t something __attribute__((packed));
   short flags __attribute__((packed));
   // here follows payload with variable length
};
...
char *payload = get_payload();
size_t payload_size = get_payload_size();//doesnt matter how
char *data = malloc(sizeof(struct packet)+payload_size);
struct packet *pkt = (struct packet *)data;
pkt->id = 123;
pkt->something = get_something();
pkt->flags = FLAG | FLAG2;
memcpy(data+sizeof(struct packet), payload, payload_size);
send(data, sizeof(struct packet)+payload_size);

现在我想用一些不错的 C++ 特性来实现它(如果有任何可以以更好的方式做到这一点)我在 C++ 中能做的最好的改变是使用 new 而不是 malloc.

Now I would like to implement this with some nice C++ features (if there are any which could do this in better way) Best change I can do in C++ is to use new instead of malloc.

char *data = new char[sizeof(struct packet)];//rest is same

好吧,这被称为对象序列化.我发现有几个例子总是使用我不能使用的 boost .在 C++ 中没有本地方法来完成这个吗?

Ok this is called object serialization.. I ve found couple of examples always using boost which I cannot use.. isnt there a native way in C++ to acomplish this?

推荐答案

没有理由创建 char*pkt*.您创建并发送一个对象,如:

There is no reason to create a char* and an pkt*. You create and send an object like:

packet pkt;  // create automatic object
pkt.id = 123;
pkt.something = get_something();
pktflags = FLAG | FLAG2;
// here we cast the address of pkt to a char* so we can send it
send(reinterpret_cast<char*>(&pkt), sizeof(packet));

由于问题已更新为将有效负载添加到 struct 数据的末尾,因此您将不得不使用在 C 中使用的相同方法.当您 new 向上指针语法将是

Since the question was updated to have a payload added to the end of the struct data you are going to have to use the same method that you did in C. When you new up the pointer the syntax would be

char * data = new char[sizeof(packet) + payload_size];

当使用 struct 时,C++ 中也不需要 struct 关键字,就像在 C 中一样.你可以按名称使用它.

Also the struct keyword is not required in C++ when using the struct like in C. You can just use it by name.

这篇关于如何在 C++ 中将结构映射到字符正确的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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