Marshaling structure with elements of a reference type and type value inside a union

The bellow code is a breakdown of the win32 source code. but i get an error

a type loading exception cannot be loaded from an assembly because it contains an object field with an offset of 0 that is incorrectly aligned or is overlapped by a field without an object

there is an S1 structure with elements value-typeand reference-type.. this structure is a member of a union that must have fieldOffset, but all S1 members cannot start with fieldOffset 0, they are a mixture of references and value type ... how can I handle this?

[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;
     }

, S1 : , . , AdminData, .

++

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; 
}
0
1

, . , , . , , .

, ? .

unsafe public struct S1  
{      
    fixed byte MsgId[Const.FieldSizeTime + 1];
    ....
}
+1

Source: https://habr.com/ru/post/1523606/


All Articles