에의 char *에서 reinterpret_cast의 사용은 sendto(..)
및 recvfrom()
를 사용하여 UDP
소켓을 통해 같은 프로그램을 실행 (동일하거나 유사한 시스템의) 다른 서버와 struct update_packet
을했다.C++ 직렬화 - 나는 구조체를 교환하고 구조체
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};
};
I는 UDP를 통해 update packet
의 인스턴스를 전송할 reinterpret_cast
를 사용하고, 다음 컴파일 (update_packet
는 struct node
의 포인터 배열을 포함) 및 적절한 목적지로 보낸다. 나는 그것을 받아
struct update_packet update_msg =
reinterpret_cast<struct update_packet>(recved_msg);
하여 디코딩 할 때
int update_packet_size = sizeof(up);
sendto(s, reinterpret_cast<const char*>(&up), update_packet_size, 0,
(struct sockaddr *)&dest_addr, sizeof(dest_addr));
는 그러나, 나는
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' 한정자가 필요 없습니다. 즉,'struct update_packet' 대신'update_packet'을 쓰면됩니다. – legends2k