如何把csharp裏面的class/struct轉換成byte array

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
使用下面的這個類,可以很方便的把類/結構轉換成byte array. 在進行socke編程的時候很有用。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;

  5. class CommonConvertion
  6. {
  7. public static byte[] StructureToByteArray(object obj)
  8. {
  9. int Length = Marshal.SizeOf(obj);
  10. byte[] bytearray = new byte[Length];
  11. IntPtr ptr = Marshal.AllocHGlobal(Length);
  12. Marshal.StructureToPtr(obj, ptr, false);
  13. Marshal.Copy(ptr, bytearray, 0, Length);
  14. Marshal.FreeHGlobal(ptr);
  15. return bytearray;
  16. }

  17. public static void ByteArrayToStructure(byte[] bytearray, ref object obj)
  18. {
  19. int Length = Marshal.SizeOf(obj);
  20. IntPtr ptr = Marshal.AllocHGlobal(Length);
  21. Marshal.Copy(bytearray, 0, ptr, Length);
  22. obj = Marshal.PtrToStructure(ptr, obj.GetType());
  23. Marshal.FreeHGlobal(ptr);
  24. }
  25. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章