StructLayoutAttribute StructLayoutAttribute StructLayoutAttribute StructLayoutAttribute Class

Definición

Le permite controlar el diseño físico de los campos de datos de una clase o una estructura en la memoria.Lets you control the physical layout of the data fields of a class or structure in memory.

public ref class StructLayoutAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class StructLayoutAttribute : Attribute
type StructLayoutAttribute = class
    inherit Attribute
Public NotInheritable Class StructLayoutAttribute
Inherits Attribute
Herencia
StructLayoutAttributeStructLayoutAttributeStructLayoutAttributeStructLayoutAttribute
Atributos

Ejemplos

En el ejemplo siguiente se muestra una declaración administrada de la GetSystemTime de función y define MySystemTime clase con LayoutKind.Explicit diseño.The following example demonstrates a managed declaration of the GetSystemTime function and defines MySystemTime class with LayoutKind.Explicit layout. GetSystemTime Obtiene la hora del sistema y se imprime en la consola.GetSystemTime gets the system time and prints to the console.

using namespace System;
using namespace System::Runtime::InteropServices;


[StructLayout(LayoutKind::Explicit,Size=16,CharSet=CharSet::Ansi)]
value class MySystemTime
{
public:

   [FieldOffset(0)]
   short wYear;

   [FieldOffset(2)]
   short wMonth;

   [FieldOffset(4)]
   short wDayOfWeek;

   [FieldOffset(6)]
   short wDay;

   [FieldOffset(8)]
   short wHour;

   [FieldOffset(10)]
   short wMinute;

   [FieldOffset(12)]
   short wSecond;

   [FieldOffset(14)]
   short wMilliseconds;
};

ref class NativeMethods
{
public:

   [DllImport("kernel32.dll")]
   static void GetSystemTime( MySystemTime * st );
};

int main()
{
   try
   {
      MySystemTime sysTime;
      NativeMethods::GetSystemTime(  &sysTime );
      Console::WriteLine( "The System time is {0}/{1}/{2} {3}:{4}:{5}", sysTime.wDay, sysTime.wMonth, sysTime.wYear, sysTime.wHour, sysTime.wMinute, sysTime.wSecond );
   }
   catch ( TypeLoadException^ e ) 
   {
      Console::WriteLine( "TypeLoadException : {0}", e->Message );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "Exception : {0}", e->Message );
   }

}

using System;
using System.Runtime.InteropServices;

namespace InteropSample
{   

   [StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
   public class MySystemTime 
   {
      [FieldOffset(0)]public ushort wYear; 
      [FieldOffset(2)]public ushort wMonth;
      [FieldOffset(4)]public ushort wDayOfWeek; 
      [FieldOffset(6)]public ushort wDay; 
      [FieldOffset(8)]public ushort wHour; 
      [FieldOffset(10)]public ushort wMinute; 
      [FieldOffset(12)]public ushort wSecond; 
      [FieldOffset(14)]public ushort wMilliseconds; 
   }

   internal static class NativeMethods
   {
      [DllImport("kernel32.dll")]
      internal static extern void GetSystemTime([MarshalAs(UnmanagedType.LPStruct)]MySystemTime st);
   };

   class TestApplication
   {      
      public static void Main()
      {
         try
         {
            MySystemTime sysTime = new MySystemTime();
            NativeMethods.GetSystemTime(sysTime);
            Console.WriteLine("The System time is {0}/{1}/{2} {3}:{4}:{5}", sysTime.wDay,
               sysTime.wMonth, sysTime.wYear, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);            
         }         
         catch(TypeLoadException e)
         {
            Console.WriteLine("TypeLoadException : " + e.Message);
         }
         catch(Exception e)
         {
            Console.WriteLine("Exception : " + e.Message);
         }
      }
   }
}
Imports System
Imports System.Runtime.InteropServices

Namespace InteropSample

   <StructLayout(LayoutKind.Explicit, Size:=16, CharSet:=CharSet.Ansi)> _
   Public Class MySystemTime
      <FieldOffset(0)> Public wYear As Short
      <FieldOffset(2)> Public wMonth As Short
      <FieldOffset(4)> Public wDayOfWeek As Short
      <FieldOffset(6)> Public wDay As Short
      <FieldOffset(8)> Public wHour As Short
      <FieldOffset(10)> Public wMinute As Short
      <FieldOffset(12)> Public wSecond As Short
      <FieldOffset(14)> Public wMilliseconds As Short
   End Class 'MySystemTime


   Friend Class NativeMethods

      <DllImport("kernel32.dll")> _
      Friend Shared Sub GetSystemTime(<MarshalAs(UnmanagedType.LPStruct)> ByVal st As MySystemTime)
      End Sub
   End Class 'NativeMethods

   Class TestApplication

      Public Shared Sub Main()
         Try
            Dim sysTime As New MySystemTime()
            NativeMethods.GetSystemTime(sysTime)
            Console.WriteLine("The System time is {0}/{1}/{2} {3}:{4}:{5}", sysTime.wDay, sysTime.wMonth, sysTime.wYear, sysTime.wHour, sysTime.wMinute, sysTime.wSecond)
         Catch e As TypeLoadException
            Console.WriteLine(("TypeLoadException : " + e.Message.ToString()))
         Catch e As Exception
            Console.WriteLine(("Exception : " + e.Message.ToString()))
         End Try
      End Sub 'Main
   End Class 'TestApplication
End Namespace 'InteropSample 

Comentarios

Este atributo se puede aplicar a clases o estructuras.You can apply this attribute to classes or structures.

Common language runtime controla el diseño físico de los campos de datos de una clase o estructura en la memoria administrada.The common language runtime controls the physical layout of the data fields of a class or structure in managed memory. Sin embargo, si desea pasar el tipo al código no administrado, puede usar el StructLayoutAttribute atributo para controlar el diseño del tipo no administrado.However, if you want to pass the type to unmanaged code, you can use the StructLayoutAttribute attribute to control the unmanaged layout of the type. Usar el atributo con LayoutKind.Sequential para forzar que los miembros que se disponen secuencialmente en el orden en que aparecen.Use the attribute with LayoutKind.Sequential to force the members to be laid out sequentially in the order they appear. Para los tipos de bits/bytes, LayoutKind.Sequential controla tanto el diseño en la memoria administrada y el diseño en memoria no administrada.For blittable types, LayoutKind.Sequential controls both the layout in managed memory and the layout in unmanaged memory. Para los tipos del espacio, controla el diseño cuando la clase o estructura se calculan las referencias a código no administrado, pero no controla el diseño en la memoria administrada.For non-blittable types, it controls the layout when the class or structure is marshaled to unmanaged code, but does not control the layout in managed memory. Usar el atributo con LayoutKind.Explicit para controlar la posición exacta de cada miembro de datos.Use the attribute with LayoutKind.Explicit to control the precise position of each data member. Esto afecta al diseño administrado y, para los tipos de tanto espacio como bits/bytes.This affects both managed and unmanaged layout, for both blittable and non-blittable types. Uso de LayoutKind.Explicit requiere el uso de la FieldOffsetAttribute atributo para indicar la posición de cada campo dentro del tipo.Using LayoutKind.Explicit requires that you use the FieldOffsetAttribute attribute to indicate the position of each field within the type.

Los compiladores de C#, Visual Basic y C++ se aplican los Sequential valor de diseño a las estructuras de forma predeterminada.C#, Visual Basic, and C++ compilers apply the Sequential layout value to structures by default. Para las clases, debe aplicar el LayoutKind.Sequential valor explícitamente.For classes, you must apply the LayoutKind.Sequential value explicitly. El Tlbimp.exe (importador de biblioteca) también se aplica el StructLayoutAttribute atributo; siempre se aplica el LayoutKind.Sequential cuando importa una biblioteca de tipos de valor.The Tlbimp.exe (Type Library Importer) also applies the StructLayoutAttribute attribute; it always applies the LayoutKind.Sequential value when it imports a type library.

Constructores

StructLayoutAttribute(Int16) StructLayoutAttribute(Int16) StructLayoutAttribute(Int16) StructLayoutAttribute(Int16)

Inicializa una nueva instancia de la clase StructLayoutAttribute con el miembro de enumeración LayoutKind especificado.Initializes a new instance of the StructLayoutAttribute class with the specified LayoutKind enumeration member.

StructLayoutAttribute(LayoutKind) StructLayoutAttribute(LayoutKind) StructLayoutAttribute(LayoutKind) StructLayoutAttribute(LayoutKind)

Inicializa una nueva instancia de la clase StructLayoutAttribute con el miembro de enumeración LayoutKind especificado.Initializes a new instance of the StructLayoutAttribute class with the specified LayoutKind enumeration member.

Campos

CharSet CharSet CharSet CharSet

Indica si las referencias de los campos de datos de cadena dentro de la clase deben calcularse como LPWSTR o LPSTR de forma predeterminada.Indicates whether string data fields within the class should be marshaled as LPWSTR or LPSTR by default.

Pack Pack Pack Pack

Controla la alineación de los campos de datos de una clase o una estructura en la memoria.Controls the alignment of data fields of a class or structure in memory.

Size Size Size Size

Indica el tamaño absoluto de la clase o estructura.Indicates the absolute size of the class or structure.

Propiedades

TypeId TypeId TypeId TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)
Value Value Value Value

Obtiene el valor de LayoutKind que especifica la forma en que está organizada la clase o estructura.Gets the LayoutKind value that specifies how the class or structure is arranged.

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Se aplica a

Consulte también: