0

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

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by __avd
0

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

0

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.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.