【发布时间】:2015-01-19 06:23:46
【问题描述】:
我正在使用sendto(..) 和recvfrom() 与通过UDP 套接字运行相同程序的其他服务器(相同或类似系统的)交换一个名为struct update_packet 的结构。
update_packet需要是通用消息格式,也就是说它的字段有预定的固定大小,结构体的大小是字段的总和。
struct node {
uint32_t IP;
uint16_t port;
int16_t nil;
uint16_t server_id;
uint16_t cost;
};
struct update_packet {
uint16_t num_update_fields;
uint16_t port;
uint32_t IP;
struct node * nodes;
update_packet() :
num_update_fields(num_nodes), IP(myIP), port(myport)
{//fill in nodes array};
};
(update_packet包含struct node的指针数组)
我使用reinterpret_cast 通过UDP 发送update packet 的实例,然后编译并发送到正确的目的地。
int update_packet_size = sizeof(up);
sendto(s, reinterpret_cast<const char*>(&up), update_packet_size, 0,
(struct sockaddr *)&dest_addr, sizeof(dest_addr));
但是,当我收到它并尝试通过
对其进行解码时struct update_packet update_msg =
reinterpret_cast<struct update_packet>(recved_msg);
我收到一个错误
In function ‘int main(int, char**)’:
error: invalid cast from type ‘char*’ to type ‘update_packet’
struct update_packet update_msg =
reinterpret_cast<struct update_packet>(recved_msg);
为什么会出现这个错误,我该如何解决这个问题?
另外,这是通过套接字在struct 的实例中交换数据的正确方法吗?如果没有,我该怎么办?我需要像http://beej.us/guide/bgnet/examples/pack2.c 那样的pack()ing 函数吗?
【问题讨论】:
-
在 C++ 中,
struct类型可以独立引用,不需要struct限定符,即您可以简单地编写update_packet而不是struct update_packet。
标签: c++ sockets serialization deserialization