簡體   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