我有从服务器的源代码下面的C结构,和许多类似:什么是最简单的字节级操作?
// 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
这些都是TCP数据包,我需要实现的东西,发射和在C#中读取它们。最干净的方法是什么?
我目前的做法涉及
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct foo { ... }
和大量的fixed
语句来读取和写入,但它感觉很笨重,而且由于数据包本身是不固定的长度,我不使用手感舒适它。此外,这是很多工作。
但是,它确实很好地描述了数据结构,并且协议可能会随时间而改变,因此这可能是维护的理想选择。
我有什么选择?只用C++编写它并使用一些.NET魔术来使用它会更容易吗?
说明:我还需要处理endian问题和空填充字符串。