I have a struct in C
typedef struct config
{
char terminal_id[4];
char update_version[6];
char sub_app[6];
char day[6];
char month[6];
char year[6];
char hours[6];
char minutes[6];
};
I want to transfer the array of config written in C (as above ) to a struct in C# , I only have byte type data receiving in C# sockets .any idea ?
Since you are in control of the structure, and know how many fields it have, it should be easy to send the strings “as is” but include the terminating
'\0'character so you know when one string ends and the next begins (or the message ends for the last string).On the receiving end just read one character at a time appending to the correct field, when you receive a character that is zero (not
'0'but the literal value0) then you know one string ends and the next begins (or the whole structure if you received the last string).You can use this as C# strings do not have to be allocated beforehand. Another solution instead of having the string-terminators transmitted, would be to first send a fixed-size integer containing the length of the string.
Edit: If the structure on the receiving C# side have the strings as fixed-size byte arrays, then you can still use the algorithm I proposed. Read one character at a time, and do e.g.
struct.buffer1[i++] = ch;. When the array is full, or you receive the string terminator, reset the counter (iin my example before) and start receiving the next string. Remember, if the string is longer than the received string, you have to continue read characters until the string ends, but just discard them.The other solution I mention, to prepend each string with its length might be more effective though, as best case you only have to do two writes on the C side and two reads on the C# side. To not have to worry about byte-order, send the length as a fixed-length text field, e.g. to send the string
"foobar"you actually send two strings" 6"and"foobar". On the receiving end, first do a single read of four characters, convert the string to an integer, and use that value as the length for the actual string.