<script type="text/javascript">
</script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
使用下面的这个类,可以很方便的把类/结构转换成byte array. 在进行socke编程的时候很有用。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Runtime.InteropServices;
- class CommonConvertion
- {
- public static byte[] StructureToByteArray(object obj)
- {
- int Length = Marshal.SizeOf(obj);
- byte[] bytearray = new byte[Length];
- IntPtr ptr = Marshal.AllocHGlobal(Length);
- Marshal.StructureToPtr(obj, ptr, false);
- Marshal.Copy(ptr, bytearray, 0, Length);
- Marshal.FreeHGlobal(ptr);
- return bytearray;
- }
- public static void ByteArrayToStructure(byte[] bytearray, ref object obj)
- {
- int Length = Marshal.SizeOf(obj);
- IntPtr ptr = Marshal.AllocHGlobal(Length);
- Marshal.Copy(bytearray, 0, ptr, Length);
- obj = Marshal.PtrToStructure(ptr, obj.GetType());
- Marshal.FreeHGlobal(ptr);
- }
- }