Click here to Skip to main content
14,428,476 members
Rate this:
Please Sign up or sign in to vote.
I Have this struct:

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 = 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

Rate this:
Please Sign up or sign in to vote.

Solution 1

Please Try this



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;
   }
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100