Reputation: 25
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
Upvotes: 0
Views: 312
Reputation: 28338
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.
Upvotes: 5
Reputation: 39451
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.
Upvotes: 0