从这种情况下我可以看到,您不需要复制
SomeByteArray到缓冲区中。您只需要从中获取句柄
SomeByteArray,将其固定,
IntPtr使用复制数据
PtrToStructure,然后释放即可。无需副本。
那将是:
NewStuff ByteArrayTonewStuff(byte[] bytes){ GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff;}通用版本:
T ByteArrayToStructure<T>(byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff;}更简单的版本(需要
unsafe切换):
unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct{ fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); }}


