I'm trying to create a structure with a fixed length char array in it see below. The field length needs to be fixed because when the structure is full it's converted to a byte array and sent to another process by an IP packet. The process on the other end need to know the length of each field so it can be decoded properly. If anyone can help or has a better idea I would appreciate the help.
Thanks in advance
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct rec
{
public ushort MsgId; // Message Id
public double TOD; // Time of Day
public ushort Day; // Day of year
public char[] sitename;
...
...
}
AlanPosted Oct 26, 2007, 2:27 PM
If it works, Gordon, I'd use the first approach.
If code is marked as 'unsafe', then it doesn't necessarily mean that it's dangerous but it does mean that the CLR cannot verify it to be typesafe. As such, the CLR will only allow it to run in a trusted environment.
However, if you want to use pointers or fixed size buffers in C#, then you can only do so in an 'unsafe' context. Both of these entail security problems because pointers can point anywhere in memory and, unlike normal arrays, fixed size arrays are not bounds-checked.
So, unless you really need its power, unsafe code is best avoided.
gordonPosted Oct 26, 2007, 12:38 PM
AlanPosted Oct 26, 2007, 12:21 PM
If, say, your fixed size array has 128 elements, then there are two possible approachs:
Approach 1
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct rec
{
public ushort MsgId; // Message Id
public double TOD; // Time of Day
public ushort Day; // Day of year
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)]
public char[] sitename;
...
...
}
Approach 2 (.NET 2.0 or later)
[StructLayout(LayoutKind.Sequential, Pack=1)]
public unsafe struct rec
{
public ushort MsgId; // Message Id
public double TOD; // Time of Day
public ushort Day; // Day of year
public fixed char sitename[128];
...
...
}