c# - 从字节数组读取 C# 中的 C/C++ 数据结构

标签 c# .net data-structures marshalling

从数据来自 C/C++ 结构的 byte[] 数组填充 C# 结构的最佳方法是什么? C 结构看起来像这样(我的 C 很生疏):

typedef OldStuff {
    CHAR Name[8];
    UInt32 User;
    CHAR Location[8];
    UInt32 TimeStamp;
    UInt32 Sequence;
    CHAR Tracking[16];
    CHAR Filler[12];
}

并且会填充这样的东西:

[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(0)]
    public string Name;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(8)]
    public uint User;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
    [FieldOffset(12)]
    public string Location;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(20)]
    public uint TimeStamp;

    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(24)]
    public uint Sequence;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
    [FieldOffset(28)]
    public string Tracking;
}

如果 OldStuff 作为 byte[] 数组传递,将 OldStuff 复制到 NewStuff 的最佳方法是什么?

我目前正在做类似下面的事情,但感觉有点笨拙。

GCHandle handle;
NewStuff MyStuff;

int BufferSize = Marshal.SizeOf(typeof(NewStuff));
byte[] buff = new byte[BufferSize];

Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);

handle = GCHandle.Alloc(buff, GCHandleType.Pinned);

MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));

handle.Free();

有没有更好的方法来完成这个?


与固定内存和使用 Marshal.PtrStructure 相比,使用 BinaryReader 类是否会带来任何性能提升?

最佳答案

据我所见,您不需要将 SomeByteArray 复制到缓冲区中。您只需从 SomeByteArray 获取句柄,固定它,使用 PtrToStructure 复制 IntPtr 数据,然后释放。无需副本。

那就是:

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));
    }
}

关于c# - 从字节数组读取 C# 中的 C/C++ 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871/

相关文章:

c# - 如何从多个流畅的 NHibernate session 工厂获取结果?

c# - 如何验证使用正确表达式调用的模拟异步方法?

c# - SQLite 作为应用程序队列,独占行锁?

.net - 在代码中更改 ELMAH 数据库

.net - 在 .Net 中访问网络摄像头时使用哪个 API/库最好?

c# - log4net AdoNetAppender 在 Application_Start() 中不工作

c# - 如何从任务栏(WPF)隐藏打开的子窗口?

c - 实现多个进程共享的数据结构是否可行?

python - 成对求和的运行时间复杂度是多少?

c - 链接列表无法正常工作