Recipe19.9.Declaring a Fixed-Size Structure with an Embedded Array


Recipe 19.9. Declaring a Fixed-Size Structure with an Embedded Array

Problem

You 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.

Solution

Use a fixed array inside of a structure:

 public unsafe struct UnsafeByteArray {     public fixed byte Data[254]; } 

Discussion

A 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:

  • You can use it only in an unsafe context.

  • You cannot declare it as a static field, only as an instance field.

  • It can be only a one-dimensional array with a lower bound of zero (i.e., a vector array).

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 Also

See the "Unsafe Code Tutorial," the "Fixed-Size Buffers," and the "Fixed Statement" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net