Skip to main content
 首页 » 编程设计

python之AutoIt中如何使用ctypes调用 'AU3_WinGetTitle'

2024年10月25日11JustinYoung

我正在尝试使用 ctypes 为 AutoIt 制作一个 python 包装器。

这是我的问题:

例如AU3_WinGetText 的原型(prototype)是:

void AU3_WinGetTitle(LPCWSTR szTitle, LPCWSTR szText, LPWSTR szRetText, int nBufSize);

我正在使用流动代码来调用该函数:

import ctypes 
from ctypes.wintypes import * 
 
AUTOIT = ctypes.windll.LoadLibrary("AutoItX3.dll") 
 
 
def win_get_title(title, text="", buf_size=200): 
    AUTOIT.AU3_WinGetTitle.argtypes = (LPCWSTR, LPCWSTR, LPWSTR, INT) 
    AUTOIT.AU3_WinGetTitle.restypes = None 
    rec_text = LPWSTR() 
    AUTOIT.AU3_WinGetTitle(LPCWSTR(title), LPCWSTR(text), 
                          ctypes.cast(ctypes.byref(rec_text), LPWSTR), 
                          INT(buf_size)) 
    res = rec_text.value 
    return res 
 
print win_get_title("[CLASS:Notepad]") 

运行这些代码后出现异常:

    res = rec_text.value 
ValueError: invalid string pointer 0x680765E0 

请您参考如下方法:

szRetText 用于接收输出文本缓冲区

import ctypes 
from ctypes.wintypes import * 
 
AUTOIT = ctypes.windll.LoadLibrary("AutoItX3.dll") 
 
 
def win_get_title(title, text="", buf_size=200): 
    # AUTOIT.AU3_WinGetTitle.argtypes = (LPCWSTR, LPCWSTR, LPWSTR, INT) 
    # AUTOIT.AU3_WinGetTitle.restypes = None 
    rec_text = ctypes.create_unicode_buffer(buf_size) 
    AUTOIT.AU3_WinGetTitle(LPCWSTR(title), LPCWSTR(text), 
                          rec_text, INT(buf_size)) 
    res = rec_text.value.rstrip() 
    return res 
 
print win_get_title("[CLASS:Notepad]")