繁体   English   中英

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

[英]how to convert byte pointer to structure

我在将字节指针转换为结构时遇到麻烦(虽然当字节指针作为参数时它隐式工作,但从不强制转换为新对象)

假设我有

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

这是一个顺序结构,将表示一个byte [],因此当我可以将该byte []分配给此结构并像xy一样使用它时,不必担心偏移量

我的问题是,当我将字节指针byte * 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
}

我希望我有道理,知道如何投射吗?

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

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

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

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

              }
        }
    }
}

暂无
暂无

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

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