Share via


Instrução fixed (Referência de C#)

O fixed instrução impede que o coletor de lixo realocando a uma variável móvel. O fixed instrução só é permitida em um não seguros contexto. Fixedtambém pode ser usado para criar fixo de buffers de tamanho.

O fixed instrução define um ponteiro para uma variável gerenciada e "pins" essa variável durante a execução da instrução. Sem fixed, ponteiros para variáveis gerenciados Movível seria de pouco uso desde a coleta de lixo pode realocar as variáveis de forma imprevisível. O compilador C# só permite que você atribua um ponteiro para uma variável gerenciada em um fixed instrução.

unsafe static void TestMethod()
{

    // Assume that the following class exists. 
    //class Point  
    //{  
    //    public int x; 
    //    public int y;  
    //} 

    // Variable pt is a managed variable, subject to garbage collection.
    Point pt = new Point();

    // Using fixed allows the address of pt members to be taken, 
    // and "pins" pt so that it is not relocated.

    fixed (int* p = &pt.x)
    {
        *p = 1;
    }        

}

Você pode inicializar um ponteiro usando uma matriz, uma seqüência de caracteres, um buffer de tamanho fixo ou o endereço de uma variável. O exemplo a seguir ilustra o uso de endereços de variáveis, matrizes e seqüências de caracteres. Para obter mais informações sobre os buffers de tamanho fixo, consulte Buffers de tamanho fixo (Guia de Programação em C#).

static unsafe void Test2()
{
    Point point = new Point();
    double[] arr = { 0, 1.5, 2.3, 3.4, 4.0, 5.9 };
    string str = "Hello World";

    // The following two assignments are equivalent. Each assigns the address 
    // of the first element in array arr to pointer p. 

    // You can initialize a pointer by using an array. 
    fixed (double* p = arr) { /*...*/ }

    // You can initialize a pointer by using the address of a variable.  
    fixed (double* p = &arr[0]) { /*...*/ }

    // The following assignment initializes p by using a string. 
    fixed (char* p = str) { /*...*/ }

    // The following assignment is not valid, because str[0] is a char,  
    // which is a value, not a variable. 
    //fixed (char* p = &str[0]) { /*...*/ } 


    // You can initialize a pointer by using the address of a variable, such 
    // as point.x or arr[5]. 
    fixed (int* p1 = &point.x)
    {
        fixed (double* p2 = &arr[5])
        {
            // Do something with p1 and p2.
        }
    }
}

Você pode inicializar várias ponteiros, desde que eles são todos do mesmo tipo.

fixed (byte* ps = srcarray, pd = dstarray) {...}

Para inicializar os ponteiros de tipos diferentes, simplesmente aninhar fixed instruções, como mostrado no exemplo a seguir.

fixed (int* p1 = &point.x)
{
    fixed (double* p2 = &arr[5])
    {
        // Do something with p1 and p2.
    }
}

Depois que o código na instrução é executado, quaisquer variáveis fixados são fixados e está sujeito à coletor de lixo. Portanto, não apontam para essas variáveis fora do fixed instrução.

Dica

Ponteiros inicializados em instruções fixas não podem ser modificados.

No modo não seguro, você pode alocar memória na pilha, onde ele não estará sujeito à coleta de lixo e, portanto, não precisa ser fixado. Para obter mais informações, consulte stackalloc.

Exemplo

    class Point
    { 
        public int x, y; 
    }

    class FixedTest2 
    {
        // Unsafe method: takes a pointer to an int. 
        unsafe static void SquarePtrParam (int* p) 
        {
            *p *= *p;
        }

        unsafe static void Main() 
        {
            Point pt = new Point();
            pt.x = 5;
            pt.y = 6;
            // Pin pt in place: 
            fixed (int* p = &pt.x) 
            {
                SquarePtrParam (p);
            }
            // pt now unpinned.
            Console.WriteLine ("{0} {1}", pt.x, pt.y);
        }
    }
    /*
    Output:
    25 6
     */

Especificação da linguagem C#

Para obter mais informações, consulte a Especificação da linguagem C#. A especificação da linguagem é a fonte definitiva para a sintaxe e o uso de C#.

Consulte também

Referência

Palavras-chave C#

unsafe (Referência de C#)

Buffers de tamanho fixo (Guia de Programação em C#)

Conceitos

Guia de Programação em C#

Outros recursos

Referência de C#