How to declare a union in C #?

Observe the following code example:

struct DDD
{
  [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 512, ArraySubType = UnmanagedType.I1)]
  byte[] x;
}

struct BBB
{
  DDD x;
}

struct CCC
{
  DDD x;
  ulong y;
  ulong z;
}

[StructLayout(LayoutKind.Explicit)]
struct AAA
{
  [FieldOffsetAttribute(0)]
  BBB a;
  [FieldOffsetAttribute(0)]
  CCC b;
}

Unfortunately, AAAyou cannot load, an attempt to execute new AAA()fails withSystem.TypeLoadException: Could not load type 'AAA' from assembly 'Shunra.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=807fc02bc4ce69db' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.

How to deal with it?

Thanks.

EDIT:

BTW. This is a stripped down version of the MINIDUMP_CALLBACK_INPUT SMID connection created by PInvokeTool (the original structure is defined in DbgHelp.h)

+3
source share
3 answers

The problem is that no matter what you specify for MarshalAsAttribute, the array is a managed entity. To make your code work, you have to get rid of the managed array. You have two options for this:

Option 1:

, DDD:

unsafe struct DDD {
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 512, ArraySubType = UnmanagedType.I1)]
    fixed byte x[512];
}

( , MarshalAsAttribute, .)

, /unsafe.

2:

512 . - 64 longs:

struct DDD {
    long x1;
    long x2;
    long x3;
    ...
}

: .

+2

, Struct BBB CCC, , BBB CCC, DDD.

struct DDD
{
  [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 512, ArraySubType = UnmanagedType.I1)]
  byte[] x;
}

struct BBB
{
  DDD x;
  public BBB(){
     x = new DDD();
  }
}

struct CCC
{
  DDD x;
  ulong y;
  ulong z;
  public CCC(){
     x = new DDD();
  }
}

[StructLayout(LayoutKind.Explicit)]
struct AAA
{
  [FieldOffsetAttribute(0)]
  BBB a;
  [FieldOffsetAttribute(0)]
  CCC b;
  public AAA(){
     a = new BBB();
     b = new CCC();
  }
}

, - DDD, , x, byte [], , , , , , int, ...

, , , .

-1

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


All Articles