需要帮助从c中的并集转换为c#

本文关键字:转换 帮助 | 更新日期: 2023-09-27 17:59:09

可能重复:
C#中的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#

您可以使用[StructLayout(LayoutKind.Explicit)]将成员显式放置在正确的偏移处。

这是我之前提供的答案的一个例子

[StructLayout(LayoutKind.Explicit)]
public struct CharUnion
{
  [FieldOffset(0)] public char UnicodeChar;
  [FieldOffset(0)] public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
  [FieldOffset(0)] public CharUnion Char;
  [FieldOffset(2)] public short Attributes;
}

C#本机不支持C/C++的并集概念。但是,您可以使用StructLayout(LayoutKind.Explicit)和FieldOffset属性来创建等效的功能。

关于union:在下面的代码中,您可以看到KernelProcessorTime具有相同的偏移量。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;
}

LargeInteger

[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;
}

免责声明:我刚刚制作了这个代码。没有测试。代码可能有错误。