I have the following C struct from the source code of a server, and many similar:
// preprocessing magic: 1-byte alignment
typedef struct AUTH_LOGON_CHALLENGE_C
{
// 4 byte header
uint8 cmd;
uint8 error;
uint16 size;
// 30 bytes
uint8 gamename[4];
uint8 version1;
uint8 version2;
uint8 version3;
uint16 build;
uint8 platform[4];
uint8 os[4];
uint8 country[4];
uint32 timezone_bias;
uint32 ip;
uint8 I_len;
// I_len bytes
uint8 I[1];
} sAuthLogonChallenge_C;
// usage (the actual code that will read my packets):
sAuthLogonChallenge_C *ch = (sAuthLogonChallenge_C*)&buf[0]; // where buf is a raw byte array
These are TCP packets, and I need to implement something that emits and reads them in C#. What's the cleanest way to do this?
My current approach involves
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct foo { ... }
and a lot of fixed
statements to read and write it, but it feels really clunky, and since the packet itself is not fixed length, I don't feel comfortable using it. Also, it's a lot of work.
However, it does describe the data structure nicely, and the protocol may change over time, so this may be ideal for maintenance.
What are my options? Would it be easier to just write it in C++ and use some .NET magic to use that?
Clarification: I also need to handle endian issues and null-padded strings.