Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中使用类似并集的结构?_C#_Unions - Fatal编程技术网

如何在C#中使用类似并集的结构?

如何在C#中使用类似并集的结构?,c#,unions,C#,Unions,我不擅长C。在使用C#调用C DLL时,我遇到了一些问题,这与union有关,出现了一个异常: System.TypeLoadException:因为它包含偏移量为0的对象字段,该字段被非对象字段错误对齐或重叠 这是.NET 3.5中的usng VS 2015 代码如下: //C code in header typedef union _UnionValue { long intValue; double flo

我不擅长C。在使用C#调用C DLL时,我遇到了一些问题,这与union有关,出现了一个异常:

System.TypeLoadException:因为它包含偏移量为0的对象字段,该字段被非对象字段错误对齐或重叠

这是.NET 3.5中的usng VS 2015

代码如下:

//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 
我查了很多类似的问题,但都没有解决我的问题


感谢您的建议。

这有帮助吗?他们有一个例子来说明这种情况,还注意到C#中的
char
占用两个字节,而不是一个字节。