C#中結(jié)構(gòu)體和字節(jié)數(shù)組轉(zhuǎn)換實現(xiàn)
最近在使用結(jié)構(gòu)體與字節(jié)數(shù)組轉(zhuǎn)化來實現(xiàn)socket間數(shù)據(jù)傳輸?,F(xiàn)在開始整理一下。對于Marshal可以查閱msdn,關(guān)于字節(jié)數(shù)組與結(jié)構(gòu)體轉(zhuǎn)代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; namespace FileSendClient { [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] struct StructDemo { public byte a; public byte c; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] public byte[] b; public byte d; public int e; } unsafe class Program { static void Main(string[] args) { StructDemo sd; sd.a = 0; sd.d = 0; sd.c = 0; sd.b = new byte[3] { 0, 0, 1 }; sd.e = 5; int size = 0; //此處使用非安全代碼來獲取到StructDemo的值 unsafe { size = Marshal.SizeOf(sd); } byte[] b = StructToBytes(sd,size); ByteToStruct(b, typeof(StructDemo)); } //將Byte轉(zhuǎn)換為結(jié)構(gòu)體類型 public static byte[] StructToBytes(object structObj,int size) { StructDemo sd; int num = 2; byte[] bytes = new byte[size]; 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); return bytes; } //將Byte轉(zhuǎn)換為結(jié)構(gòu)體類型 public static object ByteToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type); 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); return obj; } } }
相關(guān)文章
VSCode調(diào)試C#程序及附缺失.dll文件的解決辦法
這篇文章主要介紹了VSCode調(diào)試C#程序及附缺失.dll文件的解決辦法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09C#實現(xiàn)HSL顏色值轉(zhuǎn)換為RGB的方法
這篇文章主要介紹了C#實現(xiàn)HSL顏色值轉(zhuǎn)換為RGB的方法,涉及C#數(shù)值判定與轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-06-06C#實現(xiàn)將像素轉(zhuǎn)換為頁面單位的方法
這篇文章主要介紹了C#實現(xiàn)將像素轉(zhuǎn)換為頁面單位的方法,涉及C#像素轉(zhuǎn)換在圖形繪制中的技巧,需要的朋友可以參考下2015-06-06C#實現(xiàn)利用泛型將DataSet轉(zhuǎn)為Model的方法
這篇文章主要介紹了C#實現(xiàn)利用泛型將DataSet轉(zhuǎn)為Model的方法,實例分析了C#泛型的相關(guān)使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07HttpWebRequest出錯.Section=ResponseHeader Detail=CR
HttpWebRequest出錯.Section=ResponseHeader Detail=CR...2007-03-03