C#でのC++ユニオンの複製
C共用体typedefと同等のC#はありますか?C#で次のものに相当するものは何ですか?
typedef union byte_array
{
struct{byte byte1; byte byte2; byte byte3; byte byte4;};
struct{int int1; int int2;};
};byte_array
C#でのC++ユニオンの複製
C共用体typedefと同等のC#はありますか?C#で次のものに相当するものは何ですか?
typedef union byte_array
{
struct{byte byte1; byte byte2; byte byte3; byte byte4;};
struct{int int1; int int2;};
};byte_array
C#は、C /C++のユニオンの概念をネイティブにサポートしていません。ただし、StructLayout(LayoutKind.Explicit)属性とFieldOffset属性を使用して、同等の機能を作成できます。これは、intやfloatなどのプリミティブ型に対してのみ機能することに注意してください。
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
[FieldOffset(0)]
public byte byte1;
[FieldOffset(1)]
public byte byte2;
[FieldOffset(2)]
public byte byte3;
[FieldOffset(3)]
public byte byte4;
[FieldOffset(0)]
public short int1;
[FieldOffset(2)]
public short int2;
}
あなたの質問はあなたの目的が何であるかを特定していません。データをマーシャリングしてピンボークする場合は、上記の2つの答えが正しいです。
そうでない場合は、次のようにします。
class Foo
{
object bar;
public int Bar {get {return (int)bar; } }
...
}
属性を使用するStructLayout
と、次のようになります。
[StructLayout(LayoutKind.Explicit, Pack=1)]
public struct ByteArrayUnion
{
#region Byte Fields union
[FieldOffset(0)]
public byte Byte1;
[FieldOffset(1)]
public byte Byte2;
[FieldOffset(2)]
public byte Byte3;
[FieldOffset(3)]
public byte Byte4;
#endregion
#region Int Field union
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public int Int2;
#endregion
}