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