The layout of your char
array assumes that the size of wchar_t
is two bytes; it is not - here is an example of a system where the size of wchar_t
is 4
, so the size of Packet
is 10756
, not 2692
bytes: (link to a demo).
That is why your memcpy
trick from the edit presents a problem: it assumes that the layout of data in the char[]
array matches the layout of wchar_t[]
arrays, which it may or may not match. If you know that your data array has two-character elements stored in little endian format (LSB first), you can write your own function that converts the data from the source to the destination, and call it for portions of your serialized data, like this:
void bytes_to_wchar(wchar_t *dest, const unsigned char* src, size_t length) {
for (size_t i = 0 ; i != lengt ; i++) {
dest[i] = src[2*i] | (src[2*i+1] << 8);
}
}
Now you can use this function to copy data into wchar_t
arrays independently of the wchar_t
size on the target system, or the endianness of the target system:
void deserialize(const char * dat) {
bytes_to_wchar(packet_type, dat + 0, 4);
bytes_to_wchar(packet_length[0], dat + 4, 128);
bytes_to_wchar(file_name[0], dat + 132, 256);
bytes_to_wchar(template_name[0], dat + 388, 256);
bytes_to_wchar(file_name_list[0], dat + 644, 1024);
bytes_to_wchar(file_data[0], dat + 1668, 1024);
}
The shortcut of saving the data from memory and writing it back may work when you do it on the same hardware, using the same compiler. Even then it remains sensitive to small adjustments in the headers that you use and in the settings of the compiler.
If the character array that you need to copy into the struct
has a fixed layout, you need to write a function to process that layout, converting two-byte groups into wchar_t
s, four-byte groups into unsigned int
s, and so on.