将C数据结构和typedef映射到.Net

时间:2010-10-07 14:38:32

标签: .net data-structures porting

我正在尝试编写一个用于与网络协议通信的接口,但IEEE文档描述了位级别的协议,信息分割为单个字节。

处理C typedef的最佳方法是什么,例如

typedef struct {
   Nibble transportSpecific;
   Enumeration4 messageType;
   UInteger4 versionPTP;
   UInteger16 messageLength;
   UInteger8 domainNumber;
   Octet flagField[2];
   Integer64 correctionfield;
   PortIdentity sourcePortIdentity;
   UInteger16 sequenceId;
   UInteger8 controlField;
   Integer8 logMessageInterval;
} MsgHeader;

将兼容层移植到.Net?

1 个答案:

答案 0 :(得分:1)

FieldOffsetAttribute可能对您有所帮助,但无法表示小于一个字节的值。

我会使用一个字节来表示互操作目的的两个值,然后通过属性getters访问该值。

unsafe struct MsgHeader
{
    public Nibble transportSpecific;
    //Enumeration4 messageType;
    //UInteger4 versionPTP;
    // use byte as place holder for these two fields
    public byte union;
    public ushort messageLength;
    public byte domainNumber;
    public fixed byte flagField[2];
    public long correctionfield;
    public PortIdentity sourcePortIdentity;
    public ushort sequenceId;
    public byte controlField;
    public sbyte logMessageInterval;

    // access value of two fields via getters
    public byte messageType { get { return (byte)(union >> 4); } }
    public byte versionPTP { get { return (byte)(union & 0xF); } }
}
相关问题