我正在为WIN-CE平台开发C#.Net CF.在我的代码中我正在使用
int size = Marshal.SizeOf(typeof(struct_Obj));
IntPtr newptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(struct_Obj, newptr, false);
我正在尝试发送此结构信息:
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Unicode)]
public struct __NIC_STAT
{
ulong Size; // Of this structure.
public Char[] ptcDeviceName; // The device name to be queried..
ulong DeviceState; // DEVICE_STATE_XXX above
ulong DeviceState; // DEVICE_STATE_XXX above
ulong MediaType; // NdisMediumXXX
ulong MediaState; // MEDIA_STATE_XXX above
ulong PhysicalMediaType;
ulong LinkSpeed; // In 100bits/s. 10Mb/s = 100000
UInt64 PacketsSent;
UInt64 PacketsReceived;
ulong InitTime; // In milliseconds
ulong ConnectTime; // In seconds
UInt64 BytesSent; // 0 - Unknown (or not supported)
UInt64 BytesReceived; // 0 - Unknown (or not supported)
UInt64 DirectedBytesReceived;
UInt64 DirectedPacketsReceived;
ulong PacketsReceiveErrors;
ulong PacketsSendErrors;
ulong ResetCount;
ulong MediaSenseConnectCount;
ulong MediaSenseDisconnectCount;
} ;
当我在WIN-CE机器上运行代码时,我得到“不支持异常”。这两种方法都抛出异常。
任何人都可以告诉我如何找到结构大小以及如何将结构转换为Ptr而没有任何WIN-CE问题。
谢谢!
答案 0 :(得分:1)
您的结构声明不正确。 C ++ ULONG
是32位无符号类型。但在C#中,ulong
是64位。这显然是个大问题。
最重要的是,我必须承认对你使用char[]
的方式持怀疑态度。我会用UnmanagedType.LPWStr
作为字符串。
所以我会像你这样的结构:
[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;
};
我不确定为什么Marshal.SizeOf
失败了。您可能需要将ptcDeviceName
声明为IntPtr
并使用Marshal.StringToHGlobalUni
来设置值。这至少会使结构变得模糊,如果Marshal.SizeOf
仍然失败,那么你可以回到sizeof
。