reinterpret_cast가 사용되는 상황의 예를 추가하기 만하면됩니다. 라이브러리가 원시 네트워크 패킷에 대한 포인터를 제공한다고 가정 해보십시오. 데이터 구조를 이해하기 위해 구조체를 사용할 수 있습니다. 그런 다음 해당 구조체에 대한 포인터를 캐스팅합니다. 컴파일러가 여기에있는 어떤 것을 수행하고 있는지 또는 단지 메모리에서 읽지 않을 것인지를 확인하는 방법은 없습니다. 실제 상황에서는 먼저 패킷의 크기를 확인하여 구조체가 들어갈 수있는 크기인지 확인하십시오.
아래 코드에서 IP 조각 생성자는 패킷을 가져 와서 해당 포인터를 의미있는 것으로 캐스팅합니다. 아래에 정의를 추가했습니다.
누군가 reinterpret_cast를 사용하는 것이 정당하지 않다고 생각하는 사람이라면 더 나은 방법에 대해 기쁘게 생각합니다.
IPfragment::IPfragment(const byte* const pkt_data) :
ethernetHeader(reinterpret_cast< const EthernetHeader* >(pkt_data ) )
, ipHeader (reinterpret_cast< const IPheader* >(pkt_data + ETHER_HEADER_LEN) )
, payload (reinterpret_cast< const byte* >(ipHeader )
+ (ipHeader->ver_hl & 0x0f) *4)
{
}
이
이 정의를 다음과 같습니다 C는 ++ 대신 C 스타일 캐스트의 캐스트 사용의 장점
typedef uint8_t byte ;
typedef uint16_t word ;
typedef uint32_t dword ;
#define ETHER_ADDR_LEN 6 // Ethernet addresses are 6 bytes
#define ETHER_HEADER_LEN 14 // Ethernet headers are 14 bytes
#define ETHER_TYPE_IP4 8
struct EthernetHeader
{
byte etherDestHost[ETHER_ADDR_LEN]; // Destination host address
byte etherSrcHost [ETHER_ADDR_LEN]; // Source host address
word etherType; // IP? ARP? RARP? etc
};
/* 4 bytes IP address */
struct IPaddress
{
byte byte1, byte2, byte3, byte4;
};
/* IPv4 header */
struct IPheader
{
byte ver_hl ; // Version (4 bits) + Internet header length (4 bits)
byte tos ; // Type of service
word tlen ; // Total length
word identification ; // Identification
word flags_fo ; // Flags (3 bits) + Fragment offset (13 bits)
byte ttl ; // Time to live
byte proto ; // Protocol
word crc ; // Header checksum
IPaddress saddr ; // Source address
IPaddress daddr ; // Destination address
dword op_pad ; // Option + Padding
};
class IPfragment
{
public:
const IPheader* const ipHeader;
const EthernetHeader* const ethernetHeader;
const byte* const payload;
IPfragment(const byte* const pkt_data);
// rest of code omitted for brevity
}
출처
2010-06-24 08:54:18
nus
중복? [Regular cast vs. static_cast vs. dynamic_cast] (http://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast), [static_cast, dynamic_cast 및 reinterpret_cast는 언제 사용해야합니까? ?] (http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used). – Lazer