Converting byte[] to fixed byte[]

O

O.B.

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(LayoutKind.Explicit)]
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(byte[] data) {
//
// Convert data to a PDU
//
PDU pdu;
IntPtr arrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement(
data, PDU.MAX_PDU_SIZE);
pdu = (PDU)Marshal.PtrToStructure(arrayPtr, 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 = (byte)((i + 1)%256);
}
manager.processData(data);
}
 
M

Mattias Sjögren

IntPtr arrayPtr = Marshal.UnsafeAddrOfPinnedArrayElement(
data, PDU.MAX_PDU_SIZE);

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
 
O

O.B.

Mattias said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top