解決C#結(jié)構(gòu)體數(shù)組間的轉(zhuǎn)化
解決C#結(jié)構(gòu)體數(shù)組間的轉(zhuǎn)化問(wèn)題的由來(lái):在寫(xiě)C#TCP通信程序時(shí),發(fā)送數(shù)據(jù)時(shí),如果是和VC6.0等寫(xiě)的程序通信的話,很多的都是傳送結(jié)構(gòu)體,在VC6.0中可以很方便的把一個(gè)char[]數(shù)組轉(zhuǎn)換為一個(gè)結(jié)構(gòu)體,而在C#卻不能直接把byte數(shù)組轉(zhuǎn)換為結(jié)構(gòu)體,要在C#中發(fā)送結(jié)構(gòu)體,可以按以下方法實(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)化之byte數(shù)組轉(zhuǎn)結(jié)構(gòu)體:
- /**//// <summary>
- /// byte數(shù)組轉(zhuǎn)結(jié)構(gòu)體
- /// </summary>
- /// <param name="bytes">byte數(shù)組</param>
- /// <param name="type">結(jié)構(gòu)體類型</param>
- /// <returns>轉(zhuǎn)換后的結(jié)構(gòu)體</returns>
- public static object BytesToStuct(byte[] bytes,Type type)
- ...{
- //得到結(jié)構(gòu)體的大小
- int size = Marshal.SizeOf(type);
- //byte數(shù)組長(zhǎng)度小于結(jié)構(gòu)體的大小
- if (size > bytes.Length)
- ...{
- //返回空
- return null;
- }
- //分配結(jié)構(gòu)體大小的內(nèi)存空間
- IntPtr structPtr = Marshal.AllocHGlobal(size);
- //將byte數(shù)組拷到分配好的內(nèi)存空間
- Marshal.Copy(bytes,0,structPtr,size);
- //將內(nèi)存空間轉(zhuǎn)換為目標(biāo)結(jié)構(gòu)體
- object obj = Marshal.PtrToStructure(structPtr, type);
- //釋放內(nèi)存空間
- Marshal.FreeHGlobal(structPtr);
- //返回結(jié)構(gòu)體
- return obj;
- }
解決C#結(jié)構(gòu)體數(shù)組間的轉(zhuǎn)化的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你學(xué)習(xí)和了解解決C#結(jié)構(gòu)體數(shù)組間的轉(zhuǎn)化方法有所幫助。
【編輯推薦】


















