从字节数组中读取C/C 数据结构到C#
本文介绍如何将源自C/C 结构体的字节数组数据填充到C#结构体中。
使用GCHandle和Marshal
此方法分三步:
GCHandle.Alloc
固定字节数组在内存中的位置。Marshal.PtrToStructure
将固定内存地址转换为NewStuff
实例。handle.Free()
释放GCHandle
。简化代码:
<code class="language-csharp">NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); NewStuff stuff; try { stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; }</code>
泛型版本:
<code class="language-csharp">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; }</code>
更简化的版本(需要unsafe代码块):
<code class="language-csharp">unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } }</code>
BinaryReader方法
使用BinaryReader
未必比Marshal
方法性能更高。两种方法都需要数据具有正确的布局和大小才能成功转换为NewStuff
结构体。
以上是如何高效地将 C/C 数据结构从字节数组转换为 C# 结构?的详细内容。更多信息请关注PHP中文网其他相关文章!