Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping C data structures and typedefs to .Net

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?

like image 200
Greg Buehler Avatar asked Nov 14 '22 06:11

Greg Buehler


1 Answers

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); } }
}
like image 92
joncham Avatar answered Dec 09 '22 16:12

joncham