2008年5月18日星期日

.NET中进行报文编解码(byte[]->struct等)

关于报文编解码方面,常需要做byte[]->struct等操作。我总结了一下,避免大量手工拼凑字段。有更好的方法可以补充。

1. enum可以用[FlagsAttribute]来做位运算
参见http://topic.csdn.net/t/20041018/13/3466293.html

2. struct可以用[StructLayoutAttribute]和[MarshalAsAttribute]控制数据字段的物理布局
http://topic.csdn.net/t/20041018/13/3466293.html

3. 可以用以下两个非托管方法来做byte[]到struct的互相转化
System.Runtime.InteropServices.Marshal.PtrToStructure();
System.Runtime.InteropServices.Marshal.StructureToPtr();
参见
http://topic.csdn.net/u/20080510/16/994313a3-0987-4a11-9544-979be6e38583.html

没有评论: