StructLayoutAttribute and C-style union

  • Thread starter Thread starter Jim
  • Start date Start date
J

Jim

Hi all,

I am trying to create the union of a structure and a buffer. This was
used often in embedded assembly and C programs to transfer binary data
accross serial ports. Is there an equivalent in C#? Normally, just about
anything is possible, but I can't find a way around the type checking.

Please don't hold my feet to the fire on my C syntax :). It has been
years since I wrote in C. It should convey the idea.

C:
typedef struct S
{
int a;
int b;
int c;
}

typedef union U
{
S structure,
char[sizeof(S)] buffer;
}



C#:
[StructLayout(LayoutKind.Explicit, Size=8, CharSet=CharSet.Ansi, Pack=1)]
public struct StructTest
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.I8]
public long field;

[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte[] overlay;

public StrucTest ( long l ) ....
 
Is there an equivalent in C#?

In C# v2 there's a new fixed array feature that will make this a bit
easier.

In v1, I think the easiest way is to use the BitConverter class (or
manual bit shifting) to convert between the long value and a byte
array.



Mattias
 
Thanks, Mattias.

Jim


Mattias Sjögren said:
In C# v2 there's a new fixed array feature that will make this a bit
easier.

In v1, I think the easiest way is to use the BitConverter class (or
manual bit shifting) to convert between the long value and a byte
array.



Mattias
 
Back
Top