英語で読む

次の方法で共有


LayoutKind 列挙型

定義

アンマネージ コードにエクスポートするときにオブジェクトのレイアウトを制御します。

C#
public enum LayoutKind
C#
[System.Serializable]
public enum LayoutKind
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum LayoutKind
継承
LayoutKind
属性

フィールド

名前 説明
Auto 3

ランタイムは、アンマネージ メモリ内のオブジェクトのメンバーに対して適切なレイアウトを自動的に選択します。 この列挙体メンバーで定義されたオブジェクトは、マネージド コードの外に公開できません。 公開しようとすると、例外が生成されます。

Explicit 2

アンマネージ メモリ内にあるオブジェクトの各メンバーの正確な位置は、Pack フィールドの設定によって明示的に制御されます。 各メンバーは FieldOffsetAttribute を使用して、その型内のフィールドの位置を指定する必要があります。

Sequential 0

オブジェクトのメンバーは、アンマネージ メモリにエクスポートするときに表示される順番に従ってレイアウトされます。 メンバーは、Pack で指定したパッキングに従ってレイアウトされます。メンバーは非連続にできます。

次の例は、 関数のマネージド宣言をPtInRect示しています。この関数は、ポイントが四角形内にあるかどうかをチェックし、シーケンシャル レイアウトを持つ構造体と、明示的なレイアウトを持つ構造体をRect定義Pointします。

C#
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);
      }
   }
}

注釈

この列挙は と共に StructLayoutAttribute使用されます。 共通言語ランタイムでは、既定でレイアウト値が Auto 使用されます。 値に関連するレイアウト関連の問題を Auto 減らすために、C#、Visual Basic、C++ コンパイラは値型のレイアウトを指定 Sequential します。

重要

フィールドは StructLayoutAttribute.Pack データ フィールドの配置を制御するため、指定した値に関係なくレイアウトに LayoutKind 影響します。 既定では、 の Pack 値は 0 で、現在のプラットフォームの既定のパッキング サイズを示します。 たとえば、レイアウト値を Explicit 使用し、バイト境界でフィールドの配置を指定する場合、目的の結果を取得するには 1 に設定 Pack する必要があります。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0