struct和byte[]相互转换(用Marshal类实现)
生活随笔
收集整理的這篇文章主要介紹了
struct和byte[]相互转换(用Marshal类实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉自[DotNet筆記]
相當于序列化與反序列化,但是不用借助外部文件
1、struct轉換為byte[]
?2??{???
?3??int???size???=?????Marshal.SizeOf(structObj);???
?4??IntPtr???buffer???=???Marshal.AllocHGlobal(size);???
?5??try???
?6??{???
?7??Marshal.StructureToPtr(structObj,???buffer,???false);???
?8??byte[]???bytes???=???new???byte[size];???
?9??Marshal.Copy(buffer,???bytes,???0,???size);???
10??return???bytes;???
11??}???
12??finally???
13??{???
14??Marshal.FreeHGlobal(buffer);???
15??}???
16????
17??}?
?2、byte[]轉換為struct
?2??{???
?3??int???size???=?????Marshal.SizeOf(strcutType);???
?4??IntPtr???buffer???=???Marshal.AllocHGlobal(size);???
?5??try???
?6??{???
?7??Marshal.Copy(bytes,???0,???buffer,???size);???
?8??return???Marshal.PtrToStructure(buffer,???strcutType);???
?9??}???
10??finally???
11??{???
12??Marshal.FreeHGlobal(buffer);???
13??}???
14??}?
15
轉載于:https://www.cnblogs.com/tallman/archive/2007/04/23/724032.html
總結
以上是生活随笔為你收集整理的struct和byte[]相互转换(用Marshal类实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring 与 guice 的区别好玩
- 下一篇: WinXP启动时自动打开上次关机时未关闭