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