简体   繁体   English

如何将字节数组封送给结构?

[英]How do I marshal an array of bytes to a struct?

Related Question 相关问题

In the related question, I was trying to figure out the fastest way. 在相关的问题中,我试图找出最快的方法。 The method I chose in that question has become a bottle neck for me. 我在该问题中选择的方法已成为我的瓶颈。 I am reading some binary data from a file and need to put it into a managed structure definition. 我正在从文件中读取一些二进制数据,需要将其放入托管结构定义中。 No unmanaged code is involved so I'm thinking there is a better way than allocating the GCHandle. 没有涉及非托管代码,因此我认为有比分配GCHandle更好的方法。

Is there a way to just cast an array of bytes to a structure of the same size? 有没有办法将字节数组转换为相同大小的结构?

I have a method like this: 我有这样的方法:

static public T ReadStructure<T>(byte[] bytes)
    where T : struct
{
    int len = Marshal.SizeOf(typeof(T));
    IntPtr i = Marshal.AllocHGlobal(len);

    try
    {
        Marshal.Copy(bytes, 0, i, len);
        return (T)Marshal.PtrToStructure(i, typeof(T));
    }
    finally
    {
        Marshal.FreeHGlobal(i);
    }
}

Admittedly, it's not very fast--but it doesn't need to be, in my case. 诚然,这不是很快-但就我而言,并不需要如此。 Is this your current solution, and you're finding that the alloc/copy/release overhead is too slow? 这是您当前的解决方案,并且发现分配/复制/释放开销太慢了吗?

You could check out such code: 您可以查看以下代码:


struct Foo
{
  public int x;
}

public unsafe static void Main()
{
  byte[] x = new byte[] { 1, 1, 0, 0 };
  Foo f;

  fixed (byte* xPtr = x)
  {
    f = *((Fpp*)xPtr);
  }

  Console.WriteLine(f.x);
}

It's definitely very unsafe, ad you could have problems if the structure contains some more complex types. 这绝对不安全的,如果结构包含一些更复杂的类型,您可能会遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM