Possible Duplicate:
C++ union in C#
C中的代码:
typedef struct _EVENT_HEADER {
USHORT Size; // Event Size
USHORT HeaderType; // Header Type
USHORT Flags; // Flags
USHORT EventProperty; // User given event property
ULONG ThreadId; // Thread Id
ULONG ProcessId; // Process Id
LARGE_INTEGER TimeStamp; // Event Timestamp
GUID ProviderId; // Provider Id
EVENT_DESCRIPTOR EventDescriptor; // Event Descriptor
union {
struct {
ULONG KernelTime; // Kernel Mode CPU ticks
ULONG UserTime; // User mode CPU ticks
} DUMMYSTRUCTNAME;
ULONG64 ProcessorTime; // Processor Clock
// for private session events
} DUMMYUNIONNAME;
GUID ActivityId; // Activity Id
} EVENT_HEADER, *PEVENT_HEADER;
除了工会我什么都没做。如何将其转换为C#?
最佳答案
C#本身不支持联合的C / C ++概念。但是,您可以使用StructLayout(LayoutKind.Explicit)和FieldOffset属性来创建等效功能。
关于union
:在下面的代码中,您可以看到Kernel
和ProcessorTime
具有相同的偏移量。 LargeInteger也是C#中联合实现的一个很好的例子。
事件头
[StructLayout(LayoutKind.Explicit)]
public struct EventHeader
{
[FieldOffset(0)]
public ushort Size;
[FieldOffset(2)]
public ushort HeaderType;
[FieldOffset(4)]
public ushort Flags;
[FieldOffset(6)]
public ushort EventProperty;
[FieldOffset(8)]
public uint ThreadId;
[FieldOffset(12)]
public uint ProcessId;
[FieldOffset(16)]
public LargeInteger TimeStamp;
[FieldOffset(24)]
public Guid ProviderId;
[FieldOffset(40)]
public Guid EventDescriptor;
[FieldOffset(52)]
public uint KernelTime;
[FieldOffset(56)]
public uint UserTime;
[FieldOffset(52)]
public ulong ProcessorTime;
[FieldOffset(60)]
public Guid ActivityId;
}
大整数
[StructLayout(LayoutKind.Explicit, Size = 8)]
public struct LargeInteger
{
[FieldOffset(0)]
public long QuadPart;
[FieldOffset(0)]
public uint LowPart;
[FieldOffset(4)]
public uint HighPart;
}
事件描述符
[StructLayout(LayoutKind.Sequential)]
public struct EventDescriptor
{
public ushort Id;
public byte Level;
public byte Channel;
public byte LevelSeverity;
public byte Opcode;
public ushort Task;
public uint Keyword;
}
免责声明:我刚刚编写了这段代码。没有测试。该代码可能有错误。
关于c# - 需要帮助从c中的并集转换为C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6323287/