bellow code is the marshling of a native win32 code. but i get an error message
type load exception, can not load from assembly because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field
there is a structure S1 with both value-type
member and reference-type
.. this structure is a member of union which has to have fieldOffset, but all S1 members can not start from fieldOffset 0 they are a mixture of reference and value type...how can I handle that??
[StructLayout(LayoutKind.Sequential)]
public struct S1
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeMsgid + 1)]//Reference Type
public String MsgId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeTime + 1)]//Reference Type
public String SendTime;
public UInt32 SubsSeq;//Value Type
public UInt32 ServTime;//Value Type
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeFillerA1 + 1)]//Reference Type
public String Filler;
}
[StructLayout(LayoutKind.Explicit)]
public struct AdminData
{
[FieldOffset(0)] public S1 S11;// get an error because the S1 has both reference type member and value type member
[FieldOffset(0)] public S2 S22;
[FieldOffset(0)] public S3 S33;
}
I know I have to break the S1 into 2 structures, one with value-type members and the other for reference-type members..but I do not know how to do it and how to reference them in AdminData which is a union.
EDIT:
here is the c++ code
typedef struct S1
{
char MsgId [Const.FieldSizeMsgid + 1];//Reference Type
char SendTime[Const.FieldSizeTime + 1];//Reference Type
int SubsSeq;//Value Type
int ServTime;//Value Type
char Filler[Const.FieldSizeFillerA1 + 1];//Reference Type
}
union AdminData
{
S1 S11;//has both value type member and reference type member
S2 S22;//has both value type member and reference type member
S3 S33;//has both value type member and reference type member
}
typedef struct MMTPMsg
{
int Length;
short Type;
AdminData Data; //the union
long long TimeStamp;
}
As you have discovered you cannot overlay reference types on top of value types. So to implement your union, you need to use either one or the other. Your structures must contain value types and so we conclude that you must use value types exclusively.
So, how do you implement your character arrays as value types? By using a fixed size buffer.