I have some issues with marshalling script giving an exception. I have C++ structs that I try to mimic in C# for testing a system we have. The C++ struct looks like this:
#pragma pack(1)
typedef struct
{
ACE_UINT32 result;
ACE_UINT32 command;
ACE_TCHAR information[2001];
ACE_UINT16 informationLength; ///< Length of the variable information.
} MsgStructType;
#pragma pack()
in C# I declare the struct as follows:
[StructLayout(LayoutKind.Explicit, Pack = 1)]
struct MsgStruct
{
[FieldOffset(0)]
public uint result;
[FieldOffset(4)]
public uint command;
[FieldOffset(8)]
public Byte[] information;
[FieldOffset(2009)]
public ushort informationLength;
}
I use the following methods to serialize and deserialize the message.
public static T DeserializeMsg<T>(Byte[] data) where T : struct
{
int objsize = Marshal.SizeOf(typeof(T));
IntPtr buff = Marshal.AllocHGlobal(objsize);
Marshal.Copy(data, 0, buff, objsize);
T retStruct = (T)Marshal.PtrToStructure(buff, typeof(T));
Marshal.FreeHGlobal(buff);
return retStruct;
}
public static Byte[] SerializeMessage<T>(T msg) where T : struct
{
int objsize = Marshal.SizeOf(typeof(T));
Byte[] ret = new Byte[objsize];
IntPtr buff = Marshal.AllocHGlobal(objsize);
Marshal.StructureToPtr(msg, buff, true);
Marshal.Copy(buff, ret, 0, objsize);
Marshal.FreeHGlobal(buff);
return ret;
}
I manage to serialize the message, send it on udp to the same application as received and the size of data seems to be correct. Problem I get is when I try to Deserialize the message. I get the following error code:
Perhaps the method to use Byte[] is incomplete but it is the exact same class I use for serializeing and unserializeing the data. Only difference is that I go throught udp between.
Some trial and error made me come to the insight that the definition of byte[] or char[] seems to be the issue.
[StructLayout(LayoutKind.Explicit, Pack = 1)]
struct MsgStruct
{
[FieldOffset(0)]
public uint result;
[FieldOffset(4)]
public uint command;
[FieldOffset(8)]
// public Byte[] information;
// [FieldOffset(2009)]
public ushort informationLength;
}
This one can be transferred without problems between the systems. So I guess its the byte / char array I need to work on to declare correct.