如何将字节指针转换为结构

时间:2014-10-07 00:09:49

标签: c# pointers

我在将字节指针转换为结构时遇到了麻烦(当字节指针是参数时,它会隐式工作,但它不能用于转换为新对象)

假设我

[StructLayout(LayoutKind.Sequential)]
    public struct x
    {
        public y;
        public zType;
    }

这是一个表示byte []的顺序结构,所以当我可以将该byte []分配给这个结构并像x.y一样使用它而不必担心偏移

我的问题是当我将字节指针字节* ptr = byte []传递给具有此结构作为参数的方法时,它可以工作但是当我尝试正常投射它时它不起作用

//this example works fine

{
  byte[] myByteArray = new byte[];
  fixed (byte* ptr = myByteArray)
  someMethod(ptr)
}

someMethod(x myStruct)


//the next example however doesn't work
{
  byte[] myByteArray = new byte[];
  fixed (byte* ptr = myByteArray)
  x myStruct = (myStruct)ptr
}

我希望我有意义,任何想法如何施展它?

2 个答案:

答案 0 :(得分:4)

重载隐式运算符,如下所示

public unsafe static implicit operator X (byte* ptr)
{
  var myX = new x();
  x.y = *((type*)(ptr + offset));
  return myX;
}

也会使byte []运算符重载为

public unsafe static implicit operator byte[] (X myX)
{
  var myBuffer = new byte[size];
  fixed(byte* ptr = myBuffer)
  {
    *((type*)(ptr + offset)) = myX.y;
  }
  return myBuffer;
}

现在你可以做以下几乎

byte[] B = new byte[];
fixed(byte* ptr = B)
{
  X myX = ptr;
  byte[] C = X;
}

答案 1 :(得分:2)

我不确定这是否是你想要的,但这就是这样;

using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct x
        {
            public byte y;
            public byte zType;
        }

        static unsafe void Main(string[] args)
        {
              var myByteArray = new byte[4];
              myByteArray[0] = 1;
              myByteArray[1] = 2;
              myByteArray[2] = 3;
              myByteArray[3] = 4;
              fixed (byte* ptr = myByteArray)
              {
                  var myStruct = (x*)ptr;
                  //myStruct now contain 
                  //myStruct.y == 1
                  //myStruct.ztype == 2

              }
        }
    }
}