- 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);
- }
- }
如何把csharp裏面的class/struct轉換成byte array
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
使用下面的這個類,可以很方便的把類/結構轉換成byte array. 在進行socke編程的時候很有用。發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.