In C #, you can use the fixed statement to create a buffer with a fixed size array in the data structure. Use existingCode(For example, code written in other languages, pre-existing DLL, or com projects), this method is very useful. Fixed Arrays can use any attribute or modifier that allows regular structure members to use. The only restriction is that the array type must be bool, byte, Char, short, Int, long, sbyte, ushort, uint, ulong, float, or double.
Private Fixed CharName [30];
In earlier versions of C #, it is very difficult to declare a fixed size structure of the C ++ style, because the C # structure containing arrays does not contain array elements, instead, it contains references to elements.
C #2.0 added the ability to embed fixed-size arrays in struct (when used in unsafe code blocks.
For example, before C #2.0, the following struct size is 8 bytes, And the pathname array is a reference to the array allocated by the heap:
Public StructMyarray
{
Public Char[] Pathname;
Private IntReserved;
}
In C #2.0, struct can declare using an embedded array:
Public StructMyarray// This code must appear in an unsafe Block
{
Public Fixed CharPathname [128];
}
In this structure, the pathname array has a fixed size and position, so it can be used in other Insecure code.
The size of the char array of the 128 elements is 256 bytes. In a fixed char buffer, each character always occupies two bytes, regardless of the encoding. This is true even if the char buffer is enclosed in an API method or structure with charset = charset. Auto or charset = charset. ANSI. For more information, see charset.
Another common fixed-size array is the bool array. The size of the element in the bool array is always one byte. Bool arrays are not suitable for creating bit arrays or bit buffers.
Except for the memory created with stackalloc, the C # compiler and the Common Language Runtime Library (CLR) do not perform any security buffer overflow check. As with all Insecure code, use it with caution.
Unsafe buffers are different from regular arrays in the following aspects:
Insecure buffers can only be used in insecure contexts.
Insecure buffers are always vectors (or one-dimensional arrays ).
Array declaration should include counting, such as char ID [8]. Instead of char ID [].
The insecure buffer zone can only be an instance field of the structure in the insecure context.