0

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.

Is there a way to just cast an array of bytes to a structure of the same size?

4

2 回答 2

0

我有这样的方法:

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

诚然,它不是很快——但就我而言,它不需要如此。这是您当前的解决方案,并且您发现分配/复制/释放开销太慢了吗?

于 2009-07-21T15:14:11.360 回答
0

你可以查看这样的代码:


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

这绝对是非常不安全的,如果结构包含一些更复杂的类型,您可能会遇到问题。

于 2009-07-21T15:14:35.227 回答