Windows上的奇怪的Python错误,在调试器下工作

 平平安安55555_800 发布于 2022-12-29 17:51

以下代码意外地引发了异常:pywintypes.error: (6, 'GetFileInformationByHandle', 'The handle is invalid.'),即GetFileInformationByHandle无效.

奇怪的是,在Python调试器下一切正常.更奇怪的是,当我删除some_parameterGetFileInformationByHandle,错误消失.这告诉我,也许是一些内存错误,但我真的不知所措.

有些代码可能看起来没必要,但我不能在不引起异常的情况下缩小代码.

我已经在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调用约定中的第一个参数.

我在这里留下这个答案供我自己参考,以防其他人发现这个有用.

1 个回答
  • 这让我在windbg下付出了很多努力来找出原因.

    问题是,windll.kernelbase.GetFileInformationByHandle第一个句柄参数是作为一个DWORD而不是一个传递QWORD.奇怪的错误可能是由修改前4个字节的附加代码引起的rcx,这是x64调用约定中的第一个参数.

    我在这里留下这个答案供我自己参考,以防其他人发现这个有用.

    2022-12-29 17:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有