首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#中要转一个C++中union套struct的联合体,求指导啊

2013-02-19 
C#中要转一个C++中union套struct的联合体,求指点啊!C++ codestruct{unsigned int ia}Astruct{unsigned i

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)
        {
            Integer i;
            i.Value = 0x87654321;


            Console.WriteLine("H: {0:x}, L: {1:x}", i.High, i.Low);
            i.Low = 0x5678;
            i.High = 0x1234;
            Console.WriteLine("{0:x}", i.Value);
        }
    }
}


[解决办法]
http://msdn.microsoft.com/zh-cn/library/ya9bz4ha%28v=vs.80%29.aspx

热点排行