Python 内存缓冲区 pywin32

Python Memorybuffer pywin32

我得到了一些代码:

    def get_text(self, id):
        edit_hwnd = win32gui.GetDlgItem(self.hwnd, id)  # 获取窗口句柄
        time.sleep(0.2)
        self.edit_hwnd = edit_hwnd
        length = win32api.SendMessage(
             edit_hwnd, win32con.WM_GETTEXTLENGTH) + 1  # 获取窗体内容长度
        buf = win32gui.PyMakeBuffer(length)  # 准备buffer对象作为容器
        win32gui.SendMessage(edit_hwnd, win32con.WM_GETTEXT,
                         length, buf)  # 获取窗体内容放入容器
        try:
            address, length = win32gui.PyGetBufferAddressAndLen(buf)  # 获取容器的内存地址
        except ValueError:
            print('error')
            return
        text = win32gui.PyGetString(address, length)  # 取得字符串
        buf.release()
        del buf
        return text

这个在 windows.I 处获取字符串的函数需要同时这个函数来总是得到这个 value.When 值改变了,我现在做 something.But 当我这样做的时候,我的程序退出并显示错误代码 C000005.How 我可以修复它吗?

buf.release()
del buf

当我发现这个 problem.It 看起来行不通时,我添加了它。

消息 WM_GETTEXTLENGTH returns the length of the text in characters (excluding the terminating null character) and the maximum buffer length given to WM_GETTEXT 也是基于字符(包括 终止空字符)。

基于 NT 的 Windows 系统中的字符以双字节字符集 (DBCS) 编码,即每个字符两个字节。

函数 win32gui.PyMakeBuffer(length) return 是 length 字节 .

的缓冲区

所以如果lengthWM_GETTEXTLENGTH的return值,保留缓冲区应该是length * 2 + 2字节长,最大缓冲区长度给WM_GETTEXT 应该是 length + 1.