G
Guest
I'm trying to copy a structure to a byte array. I get a failure on the
Marshal.StructureToPtr() function. The structure which is as follows:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CONNECT_STRUCT
{
public byte Format;
public short sNumBytes;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=25)]
public byte[] szDatabase;
public byte cCommand;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] szVerification;
}
CONNECT_STRUCT pConnectStruct = new CONNECT_STRUCT();
pConnectStruct.Format = 2;
pConnectStruct.cCommand = 4;
pConnectStruct.sNumBytes = (short)Marshal.SizeOf(pConnectStruct);
pConnectStruct.szDatabase = StrToByteArray("MY_DATABASE");
pConnectStruct.szVerification = StrToByteArray("ABCDEFGHIJKLMNOP");
int len = Marshal.SizeOf(pConnectStruct);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(pConnectStruct, ptr, true); <===FAILS
It fails with: Type could not be marshaled because the length of an embedded
array instance does not match the declared length in the layout.
I compared "len" with the actual size of the structure and it is correct.
Any ideas?
Thanks,
Terry
Marshal.StructureToPtr() function. The structure which is as follows:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct CONNECT_STRUCT
{
public byte Format;
public short sNumBytes;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=25)]
public byte[] szDatabase;
public byte cCommand;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] szVerification;
}
CONNECT_STRUCT pConnectStruct = new CONNECT_STRUCT();
pConnectStruct.Format = 2;
pConnectStruct.cCommand = 4;
pConnectStruct.sNumBytes = (short)Marshal.SizeOf(pConnectStruct);
pConnectStruct.szDatabase = StrToByteArray("MY_DATABASE");
pConnectStruct.szVerification = StrToByteArray("ABCDEFGHIJKLMNOP");
int len = Marshal.SizeOf(pConnectStruct);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(pConnectStruct, ptr, true); <===FAILS
It fails with: Type could not be marshaled because the length of an embedded
array instance does not match the declared length in the layout.
I compared "len" with the actual size of the structure and it is correct.
Any ideas?
Thanks,
Terry