首页 >后端开发 >C++ >如何高效地将 C/C 数据结构从字节数组转换为 C# 结构?

如何高效地将 C/C 数据结构从字节数组转换为 C# 结构?

Mary-Kate Olsen
Mary-Kate Olsen原创
2025-01-19 07:36:10657浏览

How to Efficiently Convert a C/C   Data Structure from a Byte Array to a C# Struct?

从字节数组中读取C/C 数据结构到C#

本文介绍如何将源自C/C 结构体的字节数组数据填充到C#结构体中。

使用GCHandle和Marshal

此方法分三步:

  1. 使用GCHandle.Alloc固定字节数组在内存中的位置。
  2. 使用Marshal.PtrToStructure将固定内存地址转换为NewStuff实例。
  3. 转换完成后,使用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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn