有没有办法将在流或数组上收集的数据映射到数据结构,反之亦然? 在 C++ 中,这只是将指向流的指针转换为我想要使用的数据类型的问题(反之亦然) 例如:在 C++ 中
Mystruct * pMyStrct = (Mystruct*)&SomeDataStream;
pMyStrct->Item1 = 25;
int iReadData = pMyStrct->Item2;
显然,C++ 方式是相当不安全的,除非您在读取传入数据时确定流数据的质量,但对于传出数据来说非常快速和容易。
最佳答案
大多数人使用.NET序列化(有更快的二进制和更慢的XML格式化程序,它们都依赖于反射并且在一定程度上具有版本容错性)
但是,如果您想要最快(不安全)的方式 - 为什么不呢:
写作:
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();
阅读:
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
o = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct));
handle.Free();
关于c# - 将 Stream 数据映射到 C# 中的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256/