How to use a union-like struct in C#?

Viewed 66

I am not good at C#. When using C# to call a C DLL, I encountered some problems, it's about union, an exception occurred:

System.TypeLoadException: because it contains an object field at offset 0, the field has been incorrectly aligned or overlapped by a non-object field.

This is usng VS 2015 in .NET 3.5.

Here is the code:

//C code in header
typedef union _UnionValue           
{
    long intValue;                      
    double floatValue;                  
    char textValue[16];                 
    int boolValue;            
} UnionValue;

typedef struct _CustomValue
{
    long testLong;
    double testDouble;
    UnionValue maxValue;
    UnionValue minValue;
    UnionValue defaultValue;
} CustomValue;

// DLL import for C#
[StructLayout(LayoutKind.Explicit, Size = 16)]
public struct UnionValue          
{
    [FieldOffset(0)]
    public int intValue;                     
   
    [FieldOffset(0)]
    public double floatValue; 
  
    [FieldOffset(0)]
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] 
    public byte[] textValue;                 // char[16]
  
    [FieldOffset(0)]
    public int boolValue;                        
}

StructLayout(LayoutKind.Sequential)]
public struct CustomValue
{
    public int testLong;
    public double testDouble;
    public UnionValue maxValue;
    public UnionValue minValue;
    public UnionValue defaultValue;
}

// using them like this:
CustomValue myValue = new CustomValue();
myValue.testLong = 1000;
myValue.testDouble = 10.22;
            
myValue.minValue.floatValue = 100.20;
myValue.maxValue.floatValue = 1125.20;
myValue.defaultValue.floatValue = 222.333;

SetCustomValue(myValue); // a setter 

I have looked up many similar problems, but none of them solved my problem,

Grateful for any suggestions.

0 Answers
Related