StructLayoutAttribute and C-style union

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 ) ....
 
M

Mattias Sjögren

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
 
J

Jim

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top