Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Stream data to data structures in C#

Is there a way of mapping data collected on a stream or array to a data structure or vice-versa? In C++ this would simply be a matter of casting a pointer to the stream as a data type I want to use (or vice-versa for the reverse) eg: in C++

Mystruct * pMyStrct = (Mystruct*)&SomeDataStream; pMyStrct->Item1 = 25;  int iReadData = pMyStrct->Item2; 

obviously the C++ way is pretty unsafe unless you are sure of the quality of the stream data when reading incoming data, but for outgoing data is super quick and easy.

like image 232
geocoin Avatar asked Aug 05 '08 13:08

geocoin


1 Answers

Most people use .NET serialization (there is faster binary and slower XML formatter, they both depend on reflection and are version tolerant to certain degree)

However, if you want the fastest (unsafe) way - why not:

Writing:

YourStruct o = new YourStruct(); byte[] buffer = new byte[Marshal.SizeOf(typeof(YourStruct))]; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); Marshal.StructureToPtr(o, handle.AddrOfPinnedObject(), false); handle.Free(); 

Reading:

handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct)); handle.Free(); 
like image 122
lubos hasko Avatar answered Sep 24 '22 10:09

lubos hasko