Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a C# equivalent to the C union typedef?
how should i convert the following code into c#..
Can any one Please Help me with the C# equivalent Code.
C++
typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

Thank you in Advance.
Posted
Updated 27-Nov-11 18:29pm
v2

1 solution

This is done using System.Runtime.InteropServices and explicit structure layout with attributes specifying offset for each field explicitly.

C#
using System.Runtime.InteropServices;

//...

        [StructLayout(LayoutKind.Explicit)]
        struct BytePart {
            [FieldOffset(0)]
            public byte B1;
            [FieldOffset(1)]
            public byte B2;
            [FieldOffset(2)]
            public byte B3;
            [FieldOffset(3)]
            public byte B4;
        }

        [StructLayout(LayoutKind.Explicit)]
        struct ShortPart {
            [FieldOffset(0)]
            public ushort W1;
            [FieldOffset(2)]
            public ushort W2;
        }

        [StructLayout(LayoutKind.Explicit)]
        struct InAddress {
            [FieldOffset(0)]
            public BytePart BytePart;
            [FieldOffset(0)]
            public ShortPart ShortPart;
            [FieldOffset(0)]
            ulong Address;
        }


This is a fully equivalent definition without nested structures:

C#
[StructLayout(LayoutKind.Explicit)]
struct InAddress {
    //bytes:
    [FieldOffset(0)]
    public byte B1;
    [FieldOffset(1)]
    public byte B2;
    [FieldOffset(2)]
    public byte B3;
    [FieldOffset(3)]
    public byte B4;
    //words:
    [FieldOffset(0)]
    public ushort W1;
    [FieldOffset(2)]
    public ushort W2;
    //long address:
    [FieldOffset(0)]
    ulong Address;
}


See:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute.aspx[^].

—SA
 
Share this answer
 
v3
Comments
Mehdi Gholam 28-Nov-11 2:04am    
5'ed
Sergey Alexandrovich Kryukov 28-Nov-11 2:08am    
Thank you, Mehdi.
--SA
Sergey Alexandrovich Kryukov 28-Nov-11 2:14am    
I just noticed: after your vote, I passes the boundary of ¼M points, 262144.
Next "round number", half-megapoint, won't be reached soon.
Thank you!
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900