Converting byte[] to fixed byte[]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • O.B.

    Converting byte[] to fixed byte[]

    Given the following bit of code, the PtrToStructure is not correctly
    copying the data into the PDU class. After it executes, the
    pdu.buffer[] array looks nothing like the data[] array that I tried to
    copy from. Help?



    [StructLayout(La youtKind.Explic it)]
    public unsafe struct PDU {
    public const int MAX_PDU_SIZE = 1400;
    [FieldOffset(0)]
    public fixed byte buffer[MAX_PDU_SIZE];
    [FieldOffset(0)]
    public Header header;
    }

    class Manager {
    unsafe public void processData(byt e[] data) {
    //
    // Convert data to a PDU
    //
    PDU pdu;
    IntPtr arrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement(
    data, PDU.MAX_PDU_SIZ E);
    pdu = (PDU)Marshal.Pt rToStructure(ar rayPtr, typeof(PDU));

    // More processing ...
    }
    }

    static void Main(string[] args) {
    // Testing...
    Manager manager = new Manager();
    byte[] data = new byte[1400];
    for (int i = 0; i < 1400; i++) {
    data[i] = (byte)((i + 1)%256);
    }
    manager.process Data(data);
    }
  • Mattias Sjögren

    #2
    Re: Converting byte[] to fixed byte[]

    IntPtr arrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement(
    data, PDU.MAX_PDU_SIZ E);
    Here you get the address of the _last_ element in the array. So what
    you're processing is whatever is in memory after the array. The second
    parameter should probably be 0 in your case.

    Also, you never pin the data array. Therefore the address may become
    invalid at any time.


    Mattias

    --
    Mattias Sjögren [C# MVP] mattias @ mvps.org
    http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
    Please reply only to the newsgroup.

    Comment

    • O.B.

      #3
      Re: Converting byte[] to fixed byte[]

      Mattias Sjögren wrote:
      > IntPtr arrayPtr = Marshal.UnsafeA ddrOfPinnedArra yElement(
      > data, PDU.MAX_PDU_SIZ E);
      >
      Here you get the address of the _last_ element in the array. So what
      you're processing is whatever is in memory after the array. The second
      parameter should probably be 0 in your case.
      >
      Also, you never pin the data array. Therefore the address may become
      invalid at any time.
      >
      >
      Mattias
      >
      Thank you.

      Comment

      Working...