Recipe 19.9. Declaring a Fixed-Size Structure with an Embedded ArrayProblemYou require a structure to contain a fixed-size array in which the array is not stored on the managed heap; rather, the array needs to be stored inside the structure on the stack. This type of structure is useful when an unmanaged method that requires a fixed-size structure as a parameter is called from managed code. SolutionUse a fixed array inside of a structure: public unsafe struct UnsafeByteArray { public fixed byte Data[254]; } DiscussionA fixed type can be one of the following built-in types: bool, byte, sbyte, char, short, ushort, int, uint, long, ulong, float, or double. In addition, the array must be a fixed size. For example, the following code will not compile: public unsafe struct UnsafeByteArray { public fixed byte Data1[]; // Needs to be a fixed size. public fixed byte[] Data2; // Needs to be one of the // aforementioned built-in types. } A fixed-size buffer has a few other limitations, including:
Declaring a structure with an embedded array in the following manner: public struct SafeByteArray { public SafeByteArray(int size) { // Create the byte array. Data = new byte[254]; } public byte[] Data; } simply creates a structure that is 8 bytes in size. This is because arrays are reference types and are created on the managed heap while the structure, SafeByteArray, is created on the stack with a 4-byte pointer to the array on the managed heap. The UnsafeByteArray structure created in the Solution to this recipe has a size of 254 bytes in memory. This is because of the fixed keyword, which fixes the array inside of the structure as opposed to creating a pointer to an array on the managed heap. Since structures typically exist on the stack, unless they are referenced inside of a reference type, the fixed data will also reside in the stack. See AlsoSee the "Unsafe Code Tutorial," the "Fixed-Size Buffers," and the "Fixed Statement" topics in the MSDN documentation. |