Your struct is declared incorrectly. The C++ ULONG
is a 32 bit unsigned type. But in C#, ulong
is 64 bits. That's clearly a huge problem.
On top of that, I must admit to being slightly sceptical about using char[]
in the way you do. I would do it as a string with UnmanagedType.LPWStr
.
So I would have your struct like this:
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Unicode)]
public struct __NIC_STAT
{
uint Size;
[MarshalAs(UnmanagedType.LPWStr)]
public string ptcDeviceName;
uint DeviceState;
uint DeviceState;
uint MediaType;
uint MediaState;
uint PhysicalMediaType;
uint LinkSpeed;
ulong PacketsSent;
ulong PacketsReceived;
uint InitTime;
uint ConnectTime;
ulong BytesSent;
ulong BytesReceived;
ulong DirectedBytesReceived;
ulong DirectedPacketsReceived;
uint PacketsReceiveErrors;
uint PacketsSendErrors;
uint ResetCount;
uint MediaSenseConnectCount;
uint MediaSenseDisconnectCount;
};
I'm not sure why Marshal.SizeOf
is failing for you. You may need to declare ptcDeviceName
as IntPtr
and use Marshal.StringToHGlobalUni
to set the value. That at least makes the struct blittable and if Marshal.SizeOf
still fails then you can fall back on sizeof
.