Mapping C data structures and typedefs to .Net

风流意气都作罢 提交于 2019-12-23 11:47:12

问题


I'm trying to write an interface for communicating with a network protocol, but the IEEE document describes the protocol at the bit level with information split accross a single byte.

What would be the best way to go about handling a C typedef such as

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;

when porting a compatibility layer to .Net?


回答1:


FieldOffsetAttribute may be of help to you, although there is no way to represent values smaller than a byte.

I would use a byte to represent the two values for interop purposes, and then access the value via property 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); } }
}


来源:https://stackoverflow.com/questions/3882780/mapping-c-data-structures-and-typedefs-to-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!