要回答您的另一个问题,在 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;}}
}