下面的代码意外地引发了一个exception: pywintypes.error: (6, 'GetFileInformationByHandle', 'The handle is invalid.') ,即GetFileInformationByHandle不起作用。
奇怪的是,在一个Pythondebugging器下,一切正常。 更奇怪的是,当我删除some_parameter或GetFileInformationByHandle ,错误消失。 这告诉我,也许这是一些内存错误,但我真的在这里亏本。
有些代码似乎是不必要的,但是我不能在不引起exception的情况下更多地缩小代码。
我已经在Windows 7,pywin32 218.5和219上的Python 3.4.1 x64上testing过了。
import os import win32file import pywintypes from ctypes import * from ctypes.wintypes import * class BY_HANDLE_FILE_INFORMATION(Structure): _fields_ = [ ('dwFileAttributes', DWORD), ('ftCreationTime', FILETIME), ('ftLastAccessTime', FILETIME), ('ftLastWriteTime', FILETIME), ('dwVolumeSerialNumber', DWORD), ('nFileSizeHigh', DWORD), ('nFileSizeLow', DWORD), ('nNumberOfLinks', DWORD), ('nFileIndexHigh', DWORD), ('nFileIndexLow', DWORD), ] def GetFileInformationByHandle2(handle): GetFileInformationByHandle(handle) def GetFileInformationByHandle(handle): bhfi = BY_HANDLE_FILE_INFORMATION() res = windll.kernelbase.GetFileInformationByHandle(handle.handle, byref(bhfi)) if res == 0: errno = GetLastError() raise pywintypes.error(errno, 'GetFileInformationByHandle', FormatError(errno)) def open_file(path, param_1=False): return win32file.CreateFile(path, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None) def main(): path = 'test.bin' open(path, 'wb').close() h_file = open_file(path) GetFileInformationByHandle(h_file) win32file.CloseHandle(h_file) h_file = open_file(path) GetFileInformationByHandle2(h_file) win32file.CloseHandle(h_file) os.remove(path) if __name__ == '__main__': main()
这让我花了很多功夫,找出原因是什么。
问题是windll.kernelbase.GetFileInformationByHandle的第一个句柄参数是作为DWORD而不是QWORD传递的。 奇怪的错误可能是由修改rcx的前4个字节的附加代码引起的,这是x64调用约定中的第一个参数。
我将这个答案留在这里供我自己参考,并在其他人发现这个有用的情况下。