954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Fixed size structure in C#

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

niketan
Newbie Poster
4 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

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

VIeditorlover
Junior Poster
137 posts since Dec 2007
Reputation Points: 10
Solved Threads: 9
 

Import - using System.Runtime.InteropServices;

xyz p = new xyz();
 MessageBox.Show(Marshal.SizeOf(p).ToString());


Read this http://msdn.microsoft.com/en-us/library/zycewsya(VS.80).aspx

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

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

sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 

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.

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You