C#結構體數組間的轉化淺析
作者:sunny
C#結構體數組間的轉化問題:在寫C#TCP通信程序時,發送數據時,只能發送byte數組,處理起來比較麻煩,可以按本文介紹的方法實現。
C#結構體數組間的轉化問題:在寫C#TCP通信程序時,發送數據時,只能發送byte數組,處理起來比較麻煩,可以按以下方法實現:
(1)C#結構體數組轉化之定義結構體:
- //命名空間
- using System.Runtime.InteropServices;
- //注意這個屬性不能少
- [StructLayoutAttribute(
- LayoutKind.Sequential,
- CharSet=CharSet.Ansi,Pack=1)]
- struct TestStruct
- ...{
- public int c;
- //字符串,SizeConst為字符串的***長度
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
- public string str;
- //int數組,SizeConst表示數組的個數,在轉換成
- //byte數組前必須先初始化數組,再使用,初始化
- //的數組長度必須和SizeConst一致,例test = new int[6];
- [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
- public int[] test;
- }
(2)C#結構體數組轉化之結構體轉byte數組:
- /**//// <summary>
- /// 結構體轉byte數組
- /// </summary>
- /// <param name="structObj">要轉換的結構體</param>
- /// <returns>轉換后的byte數組</returns>
- public static byte[] StructToBytes(object structObj)
- ...{
- //得到結構體的大小
- int size = Marshal.SizeOf(structObj);
- //創建byte數組
- byte[] bytes = new byte[size];
- //分配結構體大小的內存空間
- IntPtr structPtr = Marshal.AllocHGlobal(size);
- //將結構體拷到分配好的內存空間
- Marshal.StructureToPtr(structObj, structPtr, false);
- //從內存空間拷到byte數組
- Marshal.Copy(structPtr, bytes, 0, size);
- //釋放內存空間
- Marshal.FreeHGlobal(structPtr);
- //返回byte數組
- return bytes;
- }
C#結構體數組轉化的問題就向你介紹到這里,希望對你學習和了解C#結構體數組轉化有所幫助。
【編輯推薦】
責任編輯:仲衡
來源:
搜狐博客