LayoutKind Enumeração
Definição
Controla o layout de um objeto quando exportado para o código não gerenciado.Controls the layout of an object when exported to unmanaged code.
public enum class LayoutKind
public enum LayoutKind
[System.Serializable]
public enum LayoutKind
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum LayoutKind
type LayoutKind =
[<System.Serializable>]
type LayoutKind =
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type LayoutKind =
Public Enum LayoutKind
- Herança
- Atributos
Campos
| Auto | 3 | O runtime escolhe automaticamente um layout adequado para os membros de um objeto na memória não gerenciada.The runtime automatically chooses an appropriate layout for the members of an object in unmanaged memory. Objetos definidos com esse membro de enumeração não podem ser expostos fora do código gerenciado.Objects defined with this enumeration member cannot be exposed outside of managed code. Tentar fazer isso gera uma exceção.Attempting to do so generates an exception. |
| Explicit | 2 | A posição exata de cada membro de um objeto na memória não gerenciada é explicitamente controlada, sujeito à configuração do campo Pack.The precise position of each member of an object in unmanaged memory is explicitly controlled, subject to the setting of the Pack field. Cada membro deve usar o FieldOffsetAttribute para indicar a posição do campo dentro do tipo.Each member must use the FieldOffsetAttribute to indicate the position of that field within the type. |
| Sequential | 0 | Os membros do objeto são dispostos sequencialmente, na ordem em que aparecem quando exportados para memória não gerenciada.The members of the object are laid out sequentially, in the order in which they appear when exported to unmanaged memory. Os membros são dispostos de acordo com a remessa especificada em Pack e podem ser não contíguos.The members are laid out according to the packing specified in Pack, and can be noncontiguous. |
Exemplos
O exemplo a seguir mostra a declaração gerenciada da PtInRect função, que verifica se um ponto está dentro de um retângulo e define uma Point estrutura com layout sequencial e uma Rect estrutura com layout explícito.The following example shows the managed declaration of the PtInRect function, which checks whether a point lies within a rectangle, and defines a Point structure with Sequential layout and a Rect structure with Explicit layout.
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 NativeMethods
{
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 = NativeMethods::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 );
}
}
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;
}
internal static class NativeMethods
{
[DllImport("user32.dll", CallingConvention=CallingConvention.StdCall)]
internal 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 = NativeMethods.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.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
Friend Class NativeMethods
<DllImport("user32.dll", CallingConvention := CallingConvention.StdCall)> _
Friend Shared Function PtInRect(ByRef r As Rect, p As Point) As Bool
End Function
End Class
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 = NativeMethods.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
Comentários
Essa enumeração é usada com StructLayoutAttribute .This enumeration is used with StructLayoutAttribute. O Common Language Runtime usa o Auto valor de layout por padrão.The common language runtime uses the Auto layout value by default. Para reduzir os problemas relacionados ao layout associados ao Auto valor, os compiladores C#, Visual Basic e C++ especificam o Sequential layout para tipos de valor.To reduce layout-related problems associated with the Auto value, C#, Visual Basic, and C++ compilers specify Sequential layout for value types.
Importante
O StructLayoutAttribute.Pack campo controla o alinhamento dos campos de dados e, portanto, afeta o layout, independentemente do LayoutKind valor especificado.The StructLayoutAttribute.Pack field controls the alignment of data fields, and thus affects the layout regardless of the LayoutKind value you specify. Por padrão, o valor de Pack é 0, que indica o tamanho de embalagem padrão para a plataforma atual.By default, the value of Pack is 0, which indicates the default packing size for the current platform. Por exemplo, ao usar o Explicit valor de layout e especificar os alinhamentos de campo em limites de bytes, você deve definir Pack como 1 para obter o resultado desejado.For example, when you use the Explicit layout value and specify field alignments on byte boundaries, you must set Pack to 1 to get the desired result.