8,737
社区成员
发帖
与我相关
我的任务
分享
public static T ReadStruct<T>(Stream stream)
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
stream.Read(buffer, 0, Marshal.SizeOf(typeof(T)));
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return typedStruct;
}
public static void WriteStruct<T>(T inputStruct, Stream stream) where T: struct
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
//Allocate the buffer to memory and pin it so that GC cannot use the space (Disable GC)
Marshal.StructureToPtr(inputStruct, handle.AddrOfPinnedObject(), false);
// copy the struct into int byte[] mem alloc
handle.Free(); //Allow GC to do its job
stream.Write(buffer, 0, buffer.Length);
}