You can declare a static unsigned char like so:
#define MSGBUFSIZE 512
static unsigned char ClientSendBuf[MSGBUFSIZE];
then copy your structure into the array like so:
memmove(&ClientSendBuf[2], &struct, sizeof(struct));
now this where it is implementation specific next. I am using Borland C++ so my sending acts like so:
ClientSocket->Socket->SendBuf(ClientSendBuf, ClientSendBuf[0]+CRC16SIZE);
The reason I use ClientSendBuf[0] is because the size of my message is stored in ClientSendBuf[0] like so:
ClientSendBuf[0] = 4 + sizeof(struct); //Byte Count
(Note: Replace struct with the name of your struct
)
I also add a CRC check to the end of my message like so:
#define CRC16SIZE 2
...
cs = CheckSum((unsigned char *)ClientSendBuf, ClientSendBuf[0]);
memmove(&ClientSendBuf[ClientSendBuf[0]], &cs, CRC16SIZE);
...
unsigned short __fastcall TFormMenu::CheckSum(unsigned char *p, int length)
{
int i;
for (cs = 0, i = 0; i < length; i++) {
cs += p[i];
}
return cs;
}
Basically all this simple CRC check is doing is summing all the bytes to determine that the correct number of bytes is sent. If the data should get mangled (which is common through buggy WiFi connections by the way), then the server should throw a CRC error.
This all assumes you have a POD struct. The static
part is not necessary, but how I did it in my particular application. I also glossed over some details. Post in the comments if you have questions. YMMV.