How do I convert c++ struct into c# ? RRS feed

  • Question

  • How do I convert following c++ struct into c# struct ?

    struct Packet


    uint16_t socket;

    uint16_t size;

    uint8_t command;

    union PacketData


    uint16_t  socket;

    uint16_t  sequence;

    uint16_t  db;

    uint8_t raw[1];

    } __attribute__ ((packed)) u;

    } __attribute__ ((packed));


    Friday, January 27, 2012 8:37 AM

All replies

  • You should post this question in the "Visual C# Language" Forum at the following address

    Anyway this kind of conversion requires you a bit of work: there is no equivalent of C++ unions in C# and structures are quite different too.
    Quoting a MSDN Magazine article

    "Structs are significantly different in C#. In C++ a struct is exactly like a class, except that the default inheritance and default access are public rather than private. In C# structs are very different from classes. Structs in C# are designed to encapsulate lightweight objects. They are value types (not reference types), so they're passed by value. In addition, they have limitations that do not apply to classes. For example, they are sealed, which means they cannot be derived from or have any base class other than System.ValueType, which is derived from Object. Structs cannot declare a default (parameterless) constructor.
    On the other hand, structs are more efficient than classes so they're perfect for the creation of lightweight objects. If you don't mind that the struct is sealed and you don't mind value semantics, using a struct may be preferable to using a class, especially for very small objects."

    Also take a look at the following links


    Luigi Bruno - Microsoft Community Contributor 2011 Award
    Friday, January 27, 2012 12:05 PM