1

我不完全确定如何在 Python 中使用 ctypes 创建这个特定结构,因为它有一个嵌套Union块。

typedef struct tagINPUT {
  DWORD type;
  union {
    MOUSEINPUT    mi;
    KEYBDINPUT    ki;
    HARDWAREINPUT hi;
  };
} INPUT, *PINPUT;

您将如何处理嵌套Union块?

4

1 回答 1

2

由于此联合从未在外部正确使用INPUT,因此您可以将其创建为嵌套类:

class INPUT(Structure):
    class _I(Union):
        _fields_ = [
            ('mi', MOUSEINPUT),
            ('ki', KEYBDINPUT),
            ('hi', HARDWAREINPUT),
        ]

    _anonymous_ = ('i', )
    _fields_ = [
        ('type', DWORD),
        ('i', _I),
    ]

即使您没有使用匿名,也可以使用input.i.hi.uMsg.

from ctypes import *
from ctypes.wintypes import *

class MOUSEINPUT(Structure):
    _fields_ = [
        ('dx', LONG),
        ('dy', LONG),
        ('mouseData', DWORD),
        ('dwFlags', DWORD),
        ('time', DWORD),
        ('dwExtraInfo', POINTER(ULONG)),
    ]

class KEYBDINPUT(Structure):
    _fields_ = [
        ('wVk', WORD),
        ('wScan', WORD),
        ('dwFlags', DWORD),
        ('time', DWORD),
        ('dwExtraInfo', POINTER(ULONG)),
    ]

class HARDWAREINPUT(Structure):
    _fields_ = [
        ('uMsg', DWORD),
        ('wParamL', WORD),
        ('wParamH', DWORD)
    ]

class INPUT(Structure):
    class _I(Union):
        _fields_ = [
            ('mi', MOUSEINPUT),
            ('ki', KEYBDINPUT),
            ('hi', HARDWAREINPUT),
        ]

    _anonymous_ = ('i', )
    _fields_ = [
        ('type', DWORD),
        ('i', _I),
    ]
于 2013-09-02T06:22:00.533 回答