Python ctypes结构在分配更多内存时被覆盖

4 投票
1 回答
1911 浏览
提问于 2025-04-16 21:22

在Python 3.2中,我正在使用ctypes.windll.kernel32.DeviceIoControl函数返回的数据创建一个结构体对象。创建完这个对象后,我可以访问结构体里的字段并获取数据。然而,如果我做一些需要使用内存的操作,比如打开一个文件,结构体里的数据就会被修改。我在结果中粘贴的输出的第一部分是我预期的结果。但是,在打开文件后,再次打印结构体的字段时,值就发生了变化。我不太明白为什么数据会被修改,或者怎么才能阻止这种情况发生。

结构体:

class DISK_GEOMETRY(ctypes.Structure):
    '''
    Disk Geometry Data Structure
    http://msdn.microsoft.com/en-us/library/aa363972(v=vs.85).aspx
    '''
    _fields_ = [("Cylinders", wintypes.LARGE_INTEGER),
                ("MediaType", wintypes.BYTE), #MEDIA_TYPE
                ("TracksPerCylinder", wintypes.DWORD),
                ("SectorsPerTrack", wintypes.DWORD),
                ("BytesPerSector", wintypes.DWORD)]


class DISK_GEOMETRY_EX(ctypes.Structure):
    '''
    Disk Geometry EX Data Structure
    http://msdn.microsoft.com/en-us/library/aa363970(v=vs.85).aspx
    '''
    _fields_ = [("Geometry", DISK_GEOMETRY),
                ("DiskSize", wintypes.LARGE_INTEGER),
                ("Data[1]", wintypes.BYTE)]

DeviceIoControl:

class DeviceIoControl:
    def __init__(self, path):
        self.path = path

    def __DeviceIoControl(self, devicehandle, IoControlCode, input, output):
        '''
        DeviceIoControl Function
        http://msdn.microsoft.com/en-us/library/aa363216(v=vs.85).aspx
        '''
        DevIoCtl = ctypes.windll.kernel32.DeviceIoControl
        DevIoCtl.argtypes = [
            wintypes.HANDLE, #HANDLE hDevice
            wintypes.DWORD, #DWORD dwIoControlCode
            wintypes.LPVOID, #LPVOID lpInBuffer
            wintypes.DWORD, #DWORD nInBufferSize
            wintypes.LPVOID, #LPVOID lpOutBuffer
            wintypes.DWORD, #DWORD nOutBufferSize
            ctypes.POINTER(wintypes.DWORD), #LPDWORD lpBytesReturned
            wintypes.LPVOID] #LPOVERLAPPED lpOverlapped
        DevIoCtl.restype = wintypes.BOOL

        if isinstance(output, int):
            output = ctypes.create_string_buffer(output)

        input_size = len(input) if input is not None else 0
        output_size = len(output)
        assert isinstance(output, ctypes.Array)

        BytesReturned = wintypes.DWORD()

        status = DevIoCtl(devicehandle, IoControlCode, input, input_size, output, output_size, BytesReturned, None)
        return output[:BytesReturned.value] if status is not 0 else -1

    def GetDriveGeometry(self):
        diskhandle = winapi.CreateHandle(
                self.path,
                winapi.NULL,
                winapi.FILE_SHARE_READ|winapi.FILE_SHARE_WRITE,
                winapi.LPSECURITY_ATTRIBUTES(),
                winapi.OPEN_EXISTING,
                winapi.FILE_ATTRIBUTE_NORMAL,
                winapi.NULL)
        if diskhandle == winapi.INVALID_HANDLE_VALUE:
            return -1

        temp = ctypes.cast(self.__DeviceIoControl(diskhandle, winioctl.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, None, 1024), ctypes.POINTER(winioctl.DISK_GEOMETRY_EX)).contents
        winapi.CloseHandle(diskhandle)
        return temp

主程序:

device = DeviceIoControl(r"\\.\PhysicalDrive0")
devicegeo = device.GetDriveGeometry()
print("Disk Size: " +str(devicegeo.DiskSize))
print("BytesPerSector: "+str(devicegeo.Geometry.BytesPerSector))
print("Cylinders: "+str(devicegeo.Geometry.Cylinders))
print("MediaType: "+str(hex(devicegeo.Geometry.MediaType)))
print("CtypesAddressOf: "+str(ctypes.addressof(devicegeo)))

with open(r"\\.\PhysicalDrive0", 'rb') as f:
    f.seek(0)
    MBRdata = f.read(512)
print("\nOpened a file\n")        

print("Disk Size: "+str(devicegeo.DiskSize))
print("BytesPerSector: "+str(devicegeo.Geometry.BytesPerSector))
print("Cylinders: "+str(devicegeo.Geometry.Cylinders))
print("MediaType: "+str(hex(devicegeo.Geometry.MediaType)))
print("CtypesAddressOf: "+str(ctypes.addressof(devicegeo)))

输出:

Disk Size: 80000000000
BytesPerSector: 512
Cylinders: 9726
MediaType: 0xc
CtypesAddressOf: 12322040

Opened a file

Disk Size: 0
BytesPerSector: 1
Cylinders: 2170477562872987649
MediaType: -0x40
CtypesAddressOf: 12322040

1 个回答

2

一些观察结果:

  1. DevIoCtl 这个函数应该用 byref(BytesReturned) 来调用。
  2. ctypes.cast 的第一个参数必须是一个“可以被看作指针的对象”。不过你现在要转换的是一个原始的 bytes 对象(来自 output[:BytesReturned.value])。
  3. 此时,从 __DeviceIoControl 返回的是一个新的 Python bytes 对象。原来的 ctypes 数组对象的引用已经不再有效。所以,它很可能已经被垃圾回收了或者被重新利用了。

顺便说一下,我玩了一下使用 ctypes 进行 Windows IOCTL 调度的事情,纯粹是为了好玩。同时也使用了 \\.\PysicalDrive0IOCTL_DISK_GET_DRIVE_GEOMETRY

我做了 这个代码片段

撰写回答