problem with Union in C#

  • Thread starter Thread starter Lorenzo
  • Start date Start date
L

Lorenzo

Hi
I have a problem converting the follow union in c#:

typedef union{
int iParam;
char acParamChar[128];
} Param;


I tried with this but don't work... why?

[StructLayout(LayoutKind.Explicit)]
struct Param
{
[FieldOffset(0)]
public int iParam;
[FieldOffset(0)]
public char []acParamChar;
}

There's someone that can help me?
Thank you.
 
Lorenzo,

Two things here. First, when you declare an array, it is declaring the
structure with pointer to the array. You want it embedded in the array.

Second, since this is an array of characters, it's really a string, so
you can declare it as such.

So, in the end, you want this:

[StructLayout(LayoutKind.Explicit, CharSet=CharSet.Ansi)]
struct Param
{
[FieldOffset(0)]
public int iParam;
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string acParamChar;
}

Notice the CharSet property on the StructLayout attribute. This
indicates that you want to use Ansi characters when converting character
types (which you want, since your unmanaged function is using the char type,
which is an 8-bit character).

Also, notice the SizeConst parameter on the MarshalAs attribute. This
will indicate the length of the array of characters which is embedded in the
structure.

Hope this helps.
 
Thank you for your time,
but when I try to instantiate the class that
contain the Param structure there's an System.TypeLoadException
i don't know why ?

I hope that you know it.
 
Back
Top