1

我有一段代码试图从旧的 qt 文件转换为 C#,但我有点不清楚下面联合中的结构中发生了什么。我不确定':'是做什么的......我猜它设置了大小,但找不到任何关于此的文档。此外,由于 C# 没有联合,因此转换此类内容的最佳做法是什么。谢谢

union uAWord
{
   uAWord()
     : m_AWord(0) {}

    struct sBcdAWord
    {
      quint32 m_O  :8;
      quint32 m_S  :2;
      quint32 m_D  :18;
      quint32 m_SS :3;
      quint32 m_P  :1;
    }
    sBcdAWord m_F;
    quint32 m_AWord;
}
4

4 回答 4

2

这就是所谓的位域。sBcdWord 部分是一个 32 位字,每个字段是该字的一部分,分别占 8、2、18、3、1:所以字布局如下:

  • Bit0-Bit7 m_0
  • Bit8-Bit9 m_S
  • Bit10-Bit27 m_D
  • Bit28-Bit30 m_ss
  • 位 31 m_P

如何在 C# 中移植它取决于您是否正在移植代码,或者您是否需要 PInvoke。在 PInvoke 的情况下,最好的解决方案可能是将 sBcdAWord 映射为 Unit32,并创建一些访问器策略来屏蔽读写。如果它是一个代码端口,使用单独的属性会很好,除非在节省内存使用方面有特殊需要。

于 2011-03-14T21:18:58.023 回答
1

该语法用于声明位域。该数字是该值的位数。参见例如http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03defbitf.htm

到 C# 的良好转换取决于我猜的情况。只要您不太注重空间,我就会在一个类中保持所有需要的值并行。

于 2011-03-14T21:19:58.310 回答
0

要回答您的另一个问题,在 C# 中您可能需要一个结构,并且您需要使用属性来从中获得类似联合的行为。

这个特定的例子可能有点像:

[StructLayout(LayoutKind.Explicit)]
struct uAWord {

    [FieldOffset(0)] 
    private uint theWord = 0;

    [FieldOffset(0)] 
    public int m_P;
    [FieldOffset(1)] 
    public int m_S;
    [FieldOffset(3)] 
    public int m_SS;
    [FieldOffset(7)] 
    public int m_O;
    [FieldOffset(18)] 
    public int m_D;

    public uAWord(uint theWord){
        this.theWord = theWord;
    }
}

指示您将LayoutKind.Explicit告诉它在内存中映射每个字段的位置,并FieldOffset(int)告诉它从哪个位开始每个字段。 有关更多详细信息,请参阅此内容。 您可以通过在构造函数中设置来分配此结构uint theWord,然后其他每个属性都将访问从不同内存地址开始的块。

不幸的是,这实际上是不正确的。您需要使用属性并进行一些位掩码/移位以使其正确。像这样:

struct uAWord {

    private uint theWord = 0;

    public int m_P {get {return (theWord & 0x01);}}
    public int m_S {get {return (theWord & 0x02) << 2;}}
    public int m_SS {get {return (theWord & 0x04) << 3;}}
    public int m_0 {get {return (theWord & 0x18) << 6;}}
}
于 2011-03-14T21:35:21.613 回答
0

初始化m_aWord0.

于 2011-03-14T21:16:05.757 回答