好的,我现在很困惑。 After my last question有几个人评论将bool改为uint我通过以下方式验证了它们的大小相同:
Console.WriteLine("sizeof bool = {0}", Marshal.SizeOf(typeof(bool)));
Console.WriteLine("sizeof uint = {0}", Marshal.SizeOf(typeof(uint)));
当然会打印出来:
sizeof bool = 4
sizeof uint = 4
那就是说,然后我打破了,并且尝试了他们的建议......将结构中的单个bool改为uint。对于我的生活我无法理解的是为什么这使它成功...
这样可行:
[StructLayout(LayoutKind.Sequential)]
public struct KEY_EVENT_RECORD
{
public bool bKeyDown;
public short wRepeatCount;
public short wVirtualKeyCode;
public short wVirtualScanCode;
public char UnicodeChar;
public int dwControlKeyState;
}
在此结构中使用时:
[StructLayout(LayoutKind.Explicit)]
public struct INPUT_RECORD
{
[FieldOffset(0)] public short EventType;
[FieldOffset(4)] public KEY_EVENT_RECORD KeyEvent;
}
但是在这种结构中,它打破了:
[StructLayout(LayoutKind.Explicit)]
public struct INPUT_RECORD
{
[FieldOffset(0)] public short EventType;
[FieldOffset(4)] public KEY_EVENT_RECORD KeyEvent;
[FieldOffset(4)] public MOUSE_EVENT_RECORD MouseEvent;
[FieldOffset(4)] public WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
[FieldOffset(4)] public MENU_EVENT_RECORD MenuEvent;
[FieldOffset(4)] public FOCUS_EVENT_RECORD FocusEvent;
}
然而,当我在KEY_EVENT_RECORD
结构中将bool bKeyDown更改为uint时,它再次开始工作......
有人可以解释一下这种行为吗?
我真的想知道它的原因,以便我可以在将来避免这种无证的功能(也就是bug)。
答案 0 :(得分:2)
尝试将字段类型设置为bool并添加属性[MarshalAs(UnmanagedType.Bool)]。
[StructLayout(LayoutKind.Sequential)]
public struct KEY_EVENT_RECORD
{
[MarshalAs(UnmanagedType.Bool)]
public bool bKeyDown;
public short wRepeatCount;
public short wVirtualKeyCode;
public short wVirtualScanCode;
public char UnicodeChar;
public int dwControlKeyState;
}
的文档
答案 1 :(得分:0)
bools是1byte - > sizeof (C# Reference)
答案 2 :(得分:0)