0

I'm working in Python trying to create a simple program that reads and write from and to a fairly simple USB device. The problem I'm having is that since PyWinUSB and PyUSB don't seem to have what I need (trying to write to the device makes things explode), I have to work from scratch using the ctypes python module and the raw dll functions in WinUSB and SetupAPI.

I've been able to get my question answered about how to define the structure that I'm passing to the function, but the problem that I'm having now is that according to the specifications of the function... well, I'll just quote it.

"DeviceInterfaceData [out]

A pointer to a caller-allocated buffer that contains, on successful return, a
completed SP_DEVICE_INTERFACE_DATA structure that identifies an interface that meets
the search parameters. The caller must set DeviceInterfaceData.cbSize to
sizeof(SP_DEVICE_INTERFACE_DATA) before calling this function."

How do I translate these requirements into Python?

The structure class I'm working with right now looks like this:

class _SP_DEVINFO_DATA(ctypes.Structure):
    _fields_ = [("cbSize", wintypes.DWORD),
                ("ClassGuid", (ctypes.c_char * 16)),
                ("DevInst", wintypes.DWORD),
                ("Reserved", wintypes.LPVOID)]

    def __init__(self, guid, inst):
        self.cbSize = ctypes.sizeof(self)
        self.ClassGuid = uuid.UUID(guid).get_bytes()
        self.DevInst = (wintypes.DWORD)(inst)
        self.Reserved = None

    def __repr__(self):
        return "_SP_DEV_INFO_DATA(cbsize={}, ClassGuid={}, DevInst={})".format(
            self.cbSize, uuid.UUID(bytes=self.ClassGuid), hex(self.DevInst))

According to what I was informed by an answer to an earlier question.

Thanks.

4

1 回答 1

0

SP_DEVINFO_DATA结构SetupDiEnumDeviceInfo. _ 有不同的结构SetupDiEnumDeviceInterfaces。在这两种情况下,您都需要构造结构,只初始化cbSize参数,然后通过引用将其传递给函数:

示例(未经测试,只是从内存中输入):

class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
    _fields_ = [('cbSize',wintypes.DWORD),
                ('InterfaceClassGuid',ctypes.c_char*16),
                ('Flags',wintypes.DWORD),
                ('Reserved',wintypes.LPVOID)]
    def __init__(self):
        self.cbSize = ctypes.sizeof(self)

PSP_DEVICE_INTERFACE_DATA = ctypes.POINTER(SP_DEVICE_INTERFACE_DATA)

i = 0
idata = SP_DEVICE_INTERFACE_DATA()

while True:
    if not SetupDiEnumDeviceInterfaces(handle,None,guid,i,ctypes.byref(idata)):
        break
    <do something with idata>
    i += 1
于 2012-10-12T16:00:26.360 回答