18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# で共用体 (union) を実現するには

Posted at

C / C++ には「共用体」(union) というのがありますが、C# にはありません。
ですが、属性 StructLayout(LayoutKind.Explicit) と FieldOffset を使って実現は可能です。
MSDN にも解説があります。

以下にサンプルを示します。


using System;
using System.Runtime.InteropServices;

// C# 共用体のテスト
public class UnionTest
{
  public static void Main()
  {
     var bytes = new TBytes();
     bytes.Word = 0x12345678;
     Console.WriteLine("{0:x}", bytes.Byte0);  // 78
     Console.WriteLine("{0:x}", bytes.Byte1);  // 56
     Console.WriteLine("{0:x}", bytes.Byte2);  // 34
     Console.WriteLine("{0:x}", bytes.Byte3);  // 12
  }
}

// 詳しい解説
// https://msdn.microsoft.com/ja-jp/library/acxa5b99.aspx
[StructLayout(LayoutKind.Explicit)]
public struct TBytes
{
  [FieldOffset(0)]
  public byte Byte0;

  [FieldOffset(1)]
  public byte Byte1;

  [FieldOffset(2)]
  public byte Byte2;

  [FieldOffset(3)]
  public byte Byte3;

  [FieldOffset(0)]
  public uint Word;
}
18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?