I am working on a TCP-Communication with another person’s program. For proper Communication he defined a Header-Struct for the Messages sent via TCP. It is defined something as following:
typedef struct
{
uint16_t number1;
uint16_t number2;
char name1[64];
char name2[64];
uint32_t size;
} headerStruct;
The struct is somehow filled, most importantly headerStruct.size sets the number of bytes following the header and is the size of the messages to be sent.
I now tried to serialize the header like this:
headerStruct sourceHeader;
// ... filling Header-Struct here ...
array<Byte>^ result = gcnew array<Byte>(520); // I tried sizeof(headerStruct) instead of '520', but then I get errors
double allreadyCopied = 0;
// serialize uint16_t 'number1'
array<Byte>^ array1 = BitConverter::GetBytes( sourceHeader.number1 );
Array::Copy(array1 , 0, result, allreadyCopied, array1 ->Length);
allreadyCopied += array1 ->Length;
// serialize uint16_t 'number2'
array<Byte>^ array2 = BitConverter::GetBytes( sourceHeader.number2 );
Array::Copy(array2 , 0, result, allreadyCopied, array2->Length);
allreadyCopied += array2->Length;
// serialize char-Array 'name1'
for (int i = 0; i < sizeof(sourceHeader.name1); i++)
{
array<Byte>^ arrayName1 = BitConverter::GetBytes( sourceHeader.name1[i] );
Array::Copy(arrayName1 , 0, result, allreadyCopied, arrayName1->Length);
allreadyCopied += arrayName1->Length;
}
// serialize char-Array 'name2'
for (int i = 0; i < sizeof(sourceHeader.name2); i++)
{
array<Byte>^ arrayName2 = BitConverter::GetBytes( sourceHeader.name2[i] );
Array::Copy(arrayName2 , 0, result, allreadyCopied, arrayName2->Length);
allreadyCopied += arrayName2->Length;
}
// serialize uint32_t 'size'
array<Byte>^ arraySize = BitConverter::GetBytes( sourceHeader.size);
Array::Copy(arraySize, 0, result, allreadyCopied, arraySize->Length);
allreadyCopied += arraySize->Length;
Now this seems to work for me, BUT:
-
I tried using sizeof(headerStruct) instead of the hardcoded value 520 for the size if the result-array. I just “calculated” it with the variable allreadyCopied. But why are they different? Where’s my error here?
-
This method is surely not very elegant. Is there a better way to do this? I tried the Marshal-Class but did not manage to get it working!
-
Somehow it feels like this approach is wrong. Is this the right way or am I completely wrong here?
Any help is appreciated a lot! Thanks!
Edit:
OK just checked:
sizeof(headerStruct); // = 136;
sizeof(char); // = 1;
sizeof(sourceHeader.name1); // = 64;
BUT
arrayName1->Length; // = 4;
Why? Very confusing: MSDN (link here) says that the returned Array should be of length 2, not 4.
OK, I googled a lot and read some articles on MSDN. I am now doing it like this:
Works for me 🙂 Hope this approach is OK the way I do it.
I used the Infos and Examples on following sites for this solution:
This should work for most Custom-Structs using native types, right? Thanks @ Hans Passant for pointing me into the right direction 🙂