logo search
CSharp_Prog_Guide

Общие сведения о небезопасном коде

Небезопасный код имеет следующие свойства.

Fixed Size Buffers

In C#, you can use the fixed statement to create a buffer with a fixed size array in a data structure. This is useful when you are working with existing code, such as code written in other languages, pre-existing DLLs or COM projects. The fixed array can take any attributes or modifiers that are allowed for regular struct members. 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 char name[30];

Remarks

In earlier versions of C#, declaring a C++ style fixed-size structure was difficult because a C# struct that contains an array does not contain the array elements, but instead contains a reference to the elements.

C# 2.0 added the ability to embed an array of fixed size in a struct when it is used in an unsafe code block.

For example, before C# 2.0, the following struct would be 8 bytes in size where the pathName array is a reference to the heap-allocated array:

public struct MyArray

{

public char[] pathName;

private int reserved;

}

In C# 2.0, a struct can be declared with an embedded array:

public struct MyArray // This code must appear in an unsafe block

{

public fixed char pathName[128];

}

In this structure, the pathName array is of fixed size and location, and can therefore be used with other unsafe code