您将如何使用ctypes重新创建此Windows API结构?

时间:2013-09-02 05:37:46

标签: python winapi ctypes

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

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

您将如何处理嵌套的Union块?

1 个答案:

答案 0 :(得分: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),
    ]