I have two functions that read a stream into a buffer and load it into a given structure.
TestStruct1 ReadRecFromStream2(Stream stream) { byte[] buffer = new byte[Marshal.SizeOf(typeof(TestStruct1))]; stream.Read(buffer, 0, 128); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { return (TestStruct1)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(TestStruct1)); } finally { handle.Free(); } } TestStruct2 ReadRecFromStream(Stream stream) { byte[] buffer = new byte[Marshal.SizeOf(typeof(TestStruct2))]; stream.Read(buffer, 0, 128); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { return (TestStruct2)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(TestStruct2)); } finally { handle.Free(); } }
I would like to combine them into a common function to take any of the structures, I'm just not sure the right way to do this.
Is it correct?
private T ReadRecFromStream<T>(Stream stream) { byte[] buffer = new byte[Marshal.SizeOf(typeof(T))]; stream.Read(buffer, 0, HeaderSize); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } }
source share