Unions in C Sharp

  • Thread starter Thread starter Fritz
  • Start date Start date
F

Fritz

Is is possible to create a C style union in C Sharp? I'm trying to call
functions in an unmanaged DLL that has a struct with unions in it as a
function parameter. I've looked at the "StructLayout" attribute and the
unmanaged code examples but I don't see anything about unions.

Regards,

Fritz
 
Hello

Use StructLayout.Explicit with FieldOffsetAttribute. See documentation of
both attributes in MSDN

Best regards,
Sherif
 
Hi Fritz,

I totally agree with Sherif. To get you started!

I have an example for you. Hope you can find it useful...

C
---
typedef union ChannelProtocol {
struct {
uint8 data2;
uint8 data1;
} b;
struct {
uint16 data12;
} w;
} CProtocol;

C#
----
[StructLayout(LayoutKind.Explicit)]
public struct ChannelProtocol
{
[StructLayout(LayoutKind.Explicit)]
public struct Sb
{
[FieldOffset(0)]
public byte data2;
[FieldOffset(1)]
public byte data1;
}

[FieldOffset(0)]
public Sb _Sb;

[StructLayout(LayoutKind.Explicit)]
public struct Sw
{
[FieldOffset(0)]
public ushort data12;
}

[FieldOffset(0)]
public Sw _Sw;
}

Cheers.
 
Yes this works when only dealing with numbers, but I have been unable to find
a way to mix numbers and strings like such:

typedef struct {
int i;
char *str;
}

In this case you need to marshall the number as Explicit but the string as
Sequential. So you would think that the solution would look something like:

[ StructLayout( LayoutKind.Explicit, Size=128 )]
public struct LITERAL_1
{
[ FieldOffset( 0 )]
public int i;
}
[ StructLayout( LayoutKind.Sequential )]
public struct LITERAL_2
{
[ MarshalAs( UnmanagedType.ByValTStr, SizeConst=128 )]
public String str;
}


[StructLayout(LayoutKind.Explicit)]
public struct LITERAL
{
[FieldOffset(0)]
public LITERAL_1 iValue;
[FieldOffset(0)]
public LITERAL_2 strValue;
}

But this errors at runtime. Is there any easy way to create a union where a
string and a number could share the same starting point?

-Greg



Chua Wen Ching said:
Hi Fritz,

I totally agree with Sherif. To get you started!

I have an example for you. Hope you can find it useful...

C
---
typedef union ChannelProtocol {
struct {
uint8 data2;
uint8 data1;
} b;
struct {
uint16 data12;
} w;
} CProtocol;

C#
----
[StructLayout(LayoutKind.Explicit)]
public struct ChannelProtocol
{
[StructLayout(LayoutKind.Explicit)]
public struct Sb
{
[FieldOffset(0)]
public byte data2;
[FieldOffset(1)]
public byte data1;
}

[FieldOffset(0)]
public Sb _Sb;

[StructLayout(LayoutKind.Explicit)]
public struct Sw
{
[FieldOffset(0)]
public ushort data12;
}

[FieldOffset(0)]
public Sw _Sw;
}

Cheers.

Sherif ElMetainy said:
Hello

Use StructLayout.Explicit with FieldOffsetAttribute. See documentation of
both attributes in MSDN

Best regards,
Sherif
 
Back
Top