Compartilhar via


Enumeração LayoutKind

 

Dica

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Controla o layout de um objeto quando exportado para o código não gerenciado.

Namespace:   System.Runtime.InteropServices
Assembly:  mscorlib (em mscorlib.dll)

Sintaxe

[SerializableAttribute]
[ComVisibleAttribute(true)]
public enum LayoutKind
[SerializableAttribute]
[ComVisibleAttribute(true)]
public enum class LayoutKind
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type LayoutKind
<SerializableAttribute>
<ComVisibleAttribute(True)>
Public Enumeration LayoutKind

Membros

Nome do membro Descrição
Auto

O tempo de execução escolhe automaticamente um layout adequado para os membros de um objeto na memória não gerenciada. Objetos definidos com esse membro de enumeração não podem ser expostos fora do código gerenciado. Tentar fazer isso gera uma exceção.

Explicit

A posição exata de cada membro de um objeto na memória não gerenciada é explicitamente controlada, sujeito à configuração do campo StructLayoutAttribute.Pack. Cada membro deve usar o FieldOffsetAttribute para indicar a posição do campo dentro do tipo.

Sequential

Os membros do objeto são dispostos sequencialmente, na ordem em que aparecem quando exportados para memória não gerenciada. Os membros são dispostos de acordo com a remessa especificada em StructLayoutAttribute.Pack e podem ser não contíguos.

Comentários

Essa enumeração é usada com StructLayoutAttribute. O common language runtime usa o Auto valor layout por padrão. Para reduzir problemas relacionados a layout associados a Auto valor, especifique os compiladores c#, Visual Basic e C++ Sequential layout para tipos de valor.

Importante

O StructLayoutAttribute.Pack campo controla o alinhamento de campos de dados e, portanto, afeta o layout independentemente do LayoutKind valor que você especificar. Por padrão, o valor de Pack é 0, que indica o padrão de remessa de tamanho para a plataforma atual. Por exemplo, quando você usa o Explicit layout e especifique alinhamentos de campo em limites de byte, você deve definir Pack como 1 para obter o resultado desejado.

Exemplos

O exemplo a seguir mostra a declaração gerenciada a PtInRect função, que verifica se um ponto está dentro de um retângulo e define uma Point estrutura com Sequential layout e um Rect estrutura com Explicit layout.

enum Bool
{
   False = 0,
   True
};
[StructLayout(LayoutKind.Sequential)]
public struct Point 
{
   public int x;
   public int y;
}   

[StructLayout(LayoutKind.Explicit)]
public struct Rect 
{
   [FieldOffset(0)] public int left;
   [FieldOffset(4)] public int top;
   [FieldOffset(8)] public int right;
   [FieldOffset(12)] public int bottom;
}   

class LibWrapper
{
   [DllImport("user32.dll", CallingConvention=CallingConvention.StdCall)]
   public static extern Bool PtInRect(ref Rect r, Point p);
};

class TestApplication
{
   public static void Main()
   {
      try
      {
         Bool bPointInRect = 0;
         Rect myRect = new Rect();
         myRect.left = 10;
         myRect.right = 100;
         myRect.top = 10;
         myRect.bottom = 100;
         Point myPoint = new Point();
         myPoint.x = 50;
         myPoint.y = 50;
         bPointInRect = LibWrapper.PtInRect(ref myRect, myPoint);
         if(bPointInRect == Bool.True)
            Console.WriteLine("Point lies within the Rect");
         else
            Console.WriteLine("Point did not lie within the Rect");
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception : " + e.Message);
      }
   }
}
'  The program shows a managed declaration of the PtInRect function and defines Point
'  structure with sequential layout and Rect structure with explicit layout. The PtInRect
'  checks the point lies within the rectangle or not.
Imports System
Imports System.Runtime.InteropServices

   Enum Bool
      [False] = 0
      [True]
   End Enum 
   <StructLayout(LayoutKind.Sequential)>  _
   Public Structure Point
      Public x As Integer
      Public y As Integer
   End Structure 

   <StructLayout(LayoutKind.Explicit)>  _   
   Public Structure Rect
      <FieldOffset(0)> Public left As Integer
      <FieldOffset(4)> Public top As Integer
      <FieldOffset(8)> Public right As Integer
      <FieldOffset(12)> Public bottom As Integer
   End Structure 


   Class LibWrapper

      <DllImport("user32.dll", CallingConvention := CallingConvention.StdCall)>  _
      Public Shared Function PtInRect(ByRef r As Rect, p As Point) As Bool
      End Function  
   End Class 'LibWrapper


   Class TestApplication

      Public Shared Sub Main()
         Try
            Dim bPointInRect As Bool = 0
            Dim myRect As New Rect()
            myRect.left = 10
            myRect.right = 100
            myRect.top = 10
            myRect.bottom = 100
            Dim myPoint As New Point()
            myPoint.x = 50
            myPoint.y = 50
            bPointInRect = LibWrapper.PtInRect(myRect, myPoint)
            If bPointInRect = Bool.True Then
               Console.WriteLine("Point lies within the Rect")
            Else
               Console.WriteLine("Point did not lie within the Rect")
            End If
         Catch e As Exception
            Console.WriteLine(("Exception : " + e.Message.ToString()))
         End Try
      End Sub 
   End Class 
enum class Bool
{
   False = 0,
   True
};


[StructLayout(LayoutKind::Sequential)]
value struct Point
{
public:
   int x;
   int y;
};


[StructLayout(LayoutKind::Explicit)]
value struct Rect
{
public:

   [FieldOffset(0)]
   int left;

   [FieldOffset(4)]
   int top;

   [FieldOffset(8)]
   int right;

   [FieldOffset(12)]
   int bottom;
};

ref class LibWrapper
{
public:

   [DllImport("user32.dll",CallingConvention=CallingConvention::StdCall)]
   static Bool PtInRect( Rect * r, Point p );
};

int main()
{
   try
   {
      Bool bPointInRect = (Bool)0;
      Rect myRect = Rect(  );
      myRect.left = 10;
      myRect.right = 100;
      myRect.top = 10;
      myRect.bottom = 100;
      Point myPoint = Point(  );
      myPoint.x = 50;
      myPoint.y = 50;
      bPointInRect = LibWrapper::PtInRect(  &myRect, myPoint );
      if ( bPointInRect == Bool::True )
            Console::WriteLine( "Point lies within the Rect" );
      else
            Console::WriteLine( "Point did not lie within the Rect" );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception : {0}", e->Message );
   }

}

Informações de Versão

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1

Confira Também

Namespace System.Runtime.InteropServices

Retornar ao início