problem with Union in C#

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
L

Lorenzo

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.
 

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