0

Can anybody tell me how do I convert the following struct to c#

typedef struct DES_ks
{
    union
    {
        DES_cblock cblock;
        /* make sure things are correct size on machines with
         * 8 byte longs */
        DES_LONG deslong[2];
    } ks[16];
} DES_key_schedule
2
  • 2
    Well, you could tell us what type DES_cblock is. I'm assuming DES_LONG is a simple integral type, but it would be helpful if you could tell us what that is too. Commented Jun 24, 2012 at 14:51
  • Oops..sorry typedef unsigned char DES_cblock[8] is DES_cblock and DES_LONG is unsigned long Commented Jun 25, 2012 at 13:19

2 Answers 2

5

You will need to look up the typedef's for DES_cblock and DES_LONG to translate this. However, to get you started, you'll want to read up on StructLayoutAttribute. The way to translate C unions into C# is to use an explicit layout structure:

[StructLayout(LayoutKind.Explicit)]
public struct DES_ks
{
  [FieldOffset(0)]
  public DES_cblock cblock;
  [FieldOffset(0)]
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  public DES_LONG[] deslong;
}

Thanks to @Konrad for fixing my temporary insanity; because you want to produce a union, you need all of the fields to overlap in memory. This is achieved in C# by telling the compiler to lay them out at the same offset, in this case 0.

Sign up to request clarification or add additional context in comments.

Comments

0

C# does not have unions.. The closest you can come is using FieldOffset. However, if your struct isn't being passed directly to external functions, you're likely better off using a more OO approach. I'd suggest just creating a struct with arrays of both types and set the one you aren't using to null.

2 Comments

This is not accurate, [LayoutKind] works just fine in regular C# code as well.
I wouldn't go as far as saying it worked "fine", but it does work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.