日期:2014-05-17  浏览次数:20890 次

C#中要转一个C++中union套struct的联合体,求指点啊!
C++ code
struct{
    unsigned int ia;
}A;
struct{
    unsigned int ib;
}B;
union{
    A a;
    B b;
}U;
转成C#中的:
[StructLayout(LayoutKind.Sequential)]
public struct A{
    public UInt32 ia;
};
[StructLayout(LayoutKind.Sequential)]
public struct B{
    public UInt32 ib;
};
[StructLayout(LayoutKind.Explicit)]
public struct U{
    [FieldOffset(0)]
    public A a;
    [FieldOffset(0)]
    public B b;
};
会报错
 An unhandled exception of type 'System.TypeLoadException' occurred in Debugger.exe
 Additional information: 未能从程序 集 Debugger, Version=1.0.1572.568, Culture=neutral, PublicKeyToken=null 中 加载类型 U,因为它在 0偏移位置处包含一个对象字段,该字段已由一个非对象字段不正确地对齐或重叠。
//////////
但是,如果把A,B改成如下就能运行正常。

[StructLayout(LayoutKind.Sequential)]
public struct A{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
    public UInt32[] ia;
};
[StructLayout(LayoutKind.Sequential)]
public struct B{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
    public UInt32[] ib;
};
但不知道能否达到相同的union效果……,请问我刚开始该怎么转才能实现union套struct的功能啊!!跪谢!
c# c++ struct union

------解决方案--------------------
使用属性访问器代替重叠的元素。
比如
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    struct Integer
    {
        public uint Value;
        public ushort High
        {
            get { return Convert.ToUInt16(Value / 0x10000); }
            set { Value = (uint)value * 0x10000 + Low; }
        }
        public ushort Low
        {
            get { return Convert.ToUInt16(Value % 0x10000); }
            set { Value = (uint)High * 0x10000 + value; }
        }
    }
    class Program
    {
        static void Main(string[] args)