Hello,
How can I define fixed size of structure in c#..
e.g.

struct xyz{
char localc[12];
short localshort;
};

I had made a c# structure like this 
[StructLayout(LayoutKind.Sequential,  Pack = 2,CharSet=CharSet.Ansi, Size = 14)]
struct xyz{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
public char[] localc;
short localshort;
}

xyz abc = new xyz();

Here i am not able to get the sizeof abc as 14 ..and got error while mashal.sizeof(abc);
How should i preallocate memory of size of structure ?
I can easily does that in c/c++ by just declaring it .. how to make this possible in c#?
and i can initialise the structure using memset in c .. whats its alternative in c#?

It will be helpful to get the solution

I am not sure about that, but unsafe could do the trick...

In .NET the char data type is is 16bit, most other languages it is 8bit. You will also need to watch out for that.

Because of this unmanaged attribute a size of char is 8 bits.

[StructLayout(LayoutKind.Sequential, Pack = 2, CharSet = CharSet.Ansi, Size = 14)]
        struct xyz
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
            public char[] localc;
            short localshort;
        }
  ...
  ...
xyz p = new xyz();
int size=Marshal.SizeOf(p);
..

So the size of struct is 14 bytes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.