Marshalling ByValArray problem showing difference between full and compact framework

Hi, I am trying to marshal a structure containing an array of System.Bytes, in code which will work on both full and compact framework. The ByValArray doesnt seem to be working as I would expect - What am I doing wrong, and how can I accomplish what I need to do

Sample code - Create a new PocketPC and Windows project, add a button, add in a using System.Runtime.InteropServices, and then this code:

[StructLayout(LayoutKind.Sequential)]
public struct structTEST
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public System.Byte[] ValId;
public System.UInt32 ValLong;
}
private void button1_Click(object sender, EventArgs e)
{
structTEST temp = new structTEST();
temp.ValId = new System.Byte[4];
temp.ValId[0] = (System.Byte)'H';
temp.ValId[1] = (System.Byte)'E';
temp.ValId[2] = (System.Byte)'L';
temp.ValId[3] = (System.Byte)'O';
temp.ValLong = (System.UInt32)0x12345678;
IntPtr buf = new IntPtr(0);
buf = Marshal.AllocCoTaskMem(100);
Marshal.StructureToPtr(temp, buf, false);
Byte[] b = new Byte[100];
Marshal.Copy(buf,b,0,20);
int i;
MessageBox.Show("Bytes...");
for (i=0;i<4;i++) {
String str = String.Format("byte {0:d} is {1:x}", i, b[ i ]);
MessageBox.Show(str);
}
MessageBox.Show("Long Bytes...");
for (i=4;i<8;i++) {
String str = String.Format("byte {0:d} is {1:x}", i, b[ i ]);
MessageBox.Show(str);
}
}PocketPC shows 4 bytes as a ptr then the long values, whereas PC version shows 48,45... etc as expected.

Thanks

[1587 byte] By [JasonE] at [2007-12-16]
# 1
Hello Jason,

This is a bug that was discovered in Beta 2 of CF about 3 months ago. The problem is actually with Marshal.StructureToPtr which also affects Marshal.PtrToStructure and Marshal.SizeOf.

If you pass the structure to native code (as either a P/Invoke or COM argument), then you will get the bits that you expect.

This bug has been fixed in our internal builds, and the fix will be in our RTM release.

Jeremy Hance
.NET Compact Framework

jhance_MS at 2007-9-9 > top of Msdn Tech,Smart Device Development,.NET Compact Framework...
# 2
Thanks - I only saw it on arrays and the only difference was the byvalarray, so assumed that was the cause...

Unfortunately I dont want to use it to pass to native code, I actually wanted to get to a byte representation of the structure - I assume there's no workaround? If not, I can wait, as its good to know if its already fixed!

Thanks for your time

JasonE at 2007-9-9 > top of Msdn Tech,Smart Device Development,.NET Compact Framework...