以下代码意外地引发了异常:pywintypes.error: (6, 'GetFileInformationByHandle', 'The handle is invalid.')
,即GetFileInformationByHandle
无效.
奇怪的是,在Python调试器下一切正常.更奇怪的是,当我删除some_parameter
或GetFileInformationByHandle
,错误消失.这告诉我,也许是一些内存错误,但我真的不知所措.
有些代码可能看起来没必要,但我不能在不引起异常的情况下缩小代码.
我已经在Windows 7,pywin32 218.5和219上的Python 3.4.1 x64上测试了这个.
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()
simonzack.. 6
这让我在windbg下付出了很多努力来找出原因.
问题是,windll.kernelbase.GetFileInformationByHandle
第一个句柄参数是作为一个DWORD
而不是一个传递QWORD
.奇怪的错误可能是由修改前4个字节的附加代码引起的rcx
,这是x64调用约定中的第一个参数.
我在这里留下这个答案供我自己参考,以防其他人发现这个有用.
这让我在windbg下付出了很多努力来找出原因.
问题是,windll.kernelbase.GetFileInformationByHandle
第一个句柄参数是作为一个DWORD
而不是一个传递QWORD
.奇怪的错误可能是由修改前4个字节的附加代码引起的rcx
,这是x64调用约定中的第一个参数.
我在这里留下这个答案供我自己参考,以防其他人发现这个有用.