Click here to Skip to main content
15,883,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I Have this struct:

C#
public struct A
{
    public int first;
}
public struct B
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
    public char[] first;
}
[StructLayout(LayoutKind.Explicit)]
public struct CUnion
{
    [FieldOffset(0)]
    public A _a;

    [FieldOffset(0)]
    public B _b;
}
public struct C
{
    public int type;
    public CUnion u;
}


but when i instance new C struct, this error

C#
C c = new C();

// Exception
// An unhandled exception of type 'System.TypeLoadException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
// Additional information: Could not load type 'CUnion' from assembly '...' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.


Any ideia?

PS: fixed memory does not apply because the memory is not senquencial
Posted
Comments
Sinisa Hajnal 3-Dec-14 8:21am    
It was long time ago, but isn't struct different from the class because it behaves like value type and has no constructor? Maybe I'm misremembering my C :)
theafien 3-Dec-14 8:33am    
i'll use this struct in pinvoke function

1 solution

Please Try this



C#
public struct A
   {
       public int first;
   }
   [StructLayout(LayoutKind.Sequential, Pack = 1)]
   public struct B
   {
       [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
       public char[] first;
   }
   [StructLayout(LayoutKind.Explicit)]
   public struct CUnion
   {
       [FieldOffset(4)]
       public A _a;

       [FieldOffset(0)]
       public B _b;
   }
   public struct C
   {
       public int type;
       public CUnion u;
   }
 
Share this answer
 
Comments
theafien 3-Dec-14 8:35am    
why _a the offset is 4?
Er. Dinesh Sharma 3-Dec-14 8:54am    
application memory is divided into blocks (in a 4-bytes base,) and every block has its own address.
theafien 3-Dec-14 9:01am    
but i want share same memory block with A and B
Er. Dinesh Sharma 3-Dec-14 9:21am    
You can not assign same memory block to same data types.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900