C,C++
구조체에서 char* 형변환 후 다시 구조체로 형변환 (struct to char*)
zingry
2018. 7. 27. 10:27
#include#include #include #pragma pack(push) #pragma pack(1) struct A{ int Size; short Cmd; int Count; };//크기 10Byte 맞춰주기위해 pragma pack()사용 #pragma pack(pop) void RecvStruct(char* StructToChar){ int Size = ((A*)StructToChar)->Size; short Cmd = ((A*)StructToChar)->Cmd; int Count = ((A*)StructToChar)->Count; // memcpy((void*)Size, StructToChar, sizeof(Size)); // memcpy((void*)Cmd, StructToChar + 4, sizeof(Cmd)); // memcpy((void*)Count, StructToChar + 6, sizeof(Count)); printf("%d\n", Size); printf("%d\n", Cmd); printf("%d\n", Count); } int main(void){ A StructA; StructA.Size = 1; StructA.Cmd = 2; StructA.Count = 3; RecvStruct((char*)&StructA); system("pause"); }
char*형으로 구조체를 넘겨주고 다시 구조체로 형변환 하여 데이터를 받아본 모습이다.
구조체를 이용하여 데이터들을 BYTE단위로 넘겨주었다.
BYTE단위로 값들을 연결하기 귀찮거나 힘들때 구조체를 이용하여 넘겨주면 편한것 같다.
memcpy로는 다시 받을수 없는것같은데 추후 더 공부할계획