I am trying to convert some C++ code into C#
#pragma pack (push, 1)
typedef struct od
{
unsigned short Reserved1;
unsigned char Reserved2;
od()
: Reserved1(0)
, Reserved2(0)
{}
} OD;
typedef struct PortValue
{
USHORT pIndex;
USHORT value;
ULONG32 ticks;
PortValue()
: pIndex(0)
, value(0)
, ticks(0)
{}
} PORT_VALUE, *PPORT_VALUE;
typedef struct _API_Data
{
unsigned long Ticks;
unsigned long SystemTime;
unsigned short DisableNotification;
unsigned short Reserved2;
unsigned short NextValue;
unsigned short Reserved3;
PORT_VALUE PortValues[500];
OD Reserved4;
_API_Data()
: Ticks(0)
, SystemTime(0)
, DisableNotification(0)
, Reserved2(0)
, NextValue(0)
, Reserved3(0)
{}
} API_DATA, *PAPI_DATA;
#pragma pack (pop)
Here is what I have come up with for C#, but as you will see below it is not right
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct od
{
public ushort Reserved1;
public byte Reserved2;
} OD;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PortValue
{
public ushort pIndex;
public ushort value;
public uint ticks;
} PORT_VALUE, *PPORT_VALUE;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct _API_Data
{
uint Ticks;
uint SystemTime;
ushort DisableNotification;
ushort Reserved2;
ushort NextValue;
ushort Reserved3;
PORT_VALUE PortValues[500];
OD Reserved4;
} API_DATA, *PAPI_DATA;
I know my C# code is wrong with how I am declaring the structs.
I don’t know how to create the equivalent of the struct name and pointer to the struct.
I also don’t know how to initialize the values like the C++ code does.
Any help would be greatly appreciated.
8
C# doesn’t have an equivalent to typedef
a struct, and you don’t need to declare pointer aliases to a struct type anyway.
Try something more like this:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct OD
{
public ushort Reserved1 = 0;
public byte Reserved2 = 0;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PORT_VALUE
{
public ushort pIndex = 0;
public ushort value = 0;
public uint ticks = 0;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct API_DATA
{
public uint Ticks = 0;
public uint SystemTime = 0;
public ushort DisableNotification = 0;
public ushort Reserved2 = 0;
public ushort NextValue = 0;
public ushort Reserved3 = 0;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 500)]
public PORT_VALUE[] PortValues = new PORT_VALUE[500];
public OD Reserved4 = new OD();
}
2