在写关于二进制文件操作程序的时候,经常要去解析文件头,在C++中我通常是使用Stream把文件读取进来后直接将二进制数据拷贝到一个文件头结构体的内存中(memcpy,此处要注意内存对齐的问题),但在C#中没有这个函数,就自己实现了个。整体来说比较麻烦,我也没想到什么其他的好办法,如果有请给我留言。
public unsafe class Unmanaged { public static T CreateStructByBytes<T>(byte[] bytes) where T : unmanaged { //申请非托管内存 IntPtr h = Marshal.AllocHGlobal(sizeof(T)); //把字节数组填充进非托管内存 Marshal.Copy(bytes, 0, h, sizeof(T)); //非托管内存转换为托管结构体 T t = (T)Marshal.PtrToStructure(h, typeof(T)); //释放非托管内存 Marshal.FreeHGlobal(h); return t; } public static byte[] CreateBytesByStruct<T>(T stru) where T : unmanaged { //申请非托管内存 IntPtr h = Marshal.AllocHGlobal(sizeof(T)); //把结构体填充进非托管内存 Marshal.StructureToPtr(stru, h, false); byte[] bytes = new byte[sizeof(T)]; //把非托管内存的数据复制到字节数组中 Marshal.Copy(h, bytes, 0, sizeof(T)); //释放非托管内存 Marshal.FreeHGlobal(h); return bytes; } }
文章评论