使用Python ctypes调用AutoIt DLL中的函数

时间:2013-11-13 02:10:55

标签: python windows autoit

我想调用AutoIt dll中的函数,我使用Python在 C:\ Program Files(x86)\ AutoIt3 \ AutoItX \ AutoItX3.dll 中找到了这些函数。我知道我可以使用win32com.client.Dispatch("AutoItX3.Control")但我无法安装应用程序或在系统中注册任何内容。

到目前为止,这就是我所在的地方:

from ctypes import *
path = r"C:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll"
autoit = windll.LoadLibrary(path)

以下是有效的方法:

autoit.AU3_WinMinimizeAll() # windows were successfully minimized.
autoit.AU3_Sleep(1000) # sleeps 1 sec.

这是我的问题,当我调用像这样的其他方法时,python崩溃了。我从Windows获取 python.exe已停止工作

autoit.AU3_WinGetHandle('Untitled - Notepad', '')

其他一些方法不会崩溃python,但只是不起作用。这个没有关闭窗口并返回0:

autoit.AU3_WinClose('Untitled - Notepad', '')

另一个返回1,但窗口仍然最小化:

autoit.AU3_WinActivate('Untitled - Notepad', '')

我已经使用Dispatch("AutoItX3.Control")测试了这些示例,一切都按预期工作。

似乎应该返回除字符串以外的东西的方法正在崩溃python。但是,像WinClose这样的其他人甚至都没有工作......

提前感谢您的帮助!

编辑:

使用unicode字符串时,这些方法现在正在运行:

autoit.AU3_WinClose(u'Untitled - Notepad', u'')
autoit.AU3_WinActivate(u'Untitled - Notepad', u'')

我找到了AU3_WinGetHandle的原型:

  

AU3_API void WINAPI AU3_WinGetHandle(const char szTitle,   / [in,defaultvalue(“”)] * / const char * szText,char * szRetText,int   nBufSize);

现在我可以使用以下代码检索返回值!

from ctypes.wintypes import LPCWSTR
s = LPCWSTR(u'')
print AU3_WinGetHandle(u'Untitled - Notepad', u'', s, 100) # prints 1
print s.value # prints '000705E0'!

感谢那些帮助我的人!

2 个答案:

答案 0 :(得分:4)

它是否适用于unicode字符串?

autoit.AU3_WinClose(u'Untitled - Notepad', u'')

autoit.AU3_WinActivate(u'Untitled - Notepad', u'')

实际上,您可能必须显式创建unicode缓冲区,例如:

autoit.AU3_WinClose(create_unicode_buffer('Untitled - Notepad'), create_unicode_buffer(''))

通过一些谷歌搜索,看起来AU3_WinGetHandle需要4个参数,而不是2.所以你需要解决这个问题。

答案 1 :(得分:4)

如果你有想要调用的函数的原型,那么我们可以帮助你调试调用而不需要猜测。或者,更重要的是,我们不会拥有来帮助您调试调用,因为您可以让ctypes为您执行此操作。

请参阅文档中的Specifying the required argument types

例如,假设该函数看起来像这样(只是随机猜测!):

void AU3_WinClose(LPCWSTR name, LPCWSTR someotherthing);

你可以这样做:

autoit.AU3_WinClose.argtypes = (LPCWSTR, LPCWSTR)
autoit.AU3_WinClose.restype = None

如果你这样做,ctypes将尝试将你的参数转换为指定的类型(LPWSTR,它是指向用于Windows UTF-16字符串的宽字符的指针),如果可以的话,或者如果它不能引发异常,并且不会期望任何回报值。

如果你这样做,ctypes将尝试猜测正确的事情,将你的参数转换为,可能猜错了,并尝试将不存在的返回值解释为int 。所以,它通常会崩溃,直到你设法准确猜出要抛出的类型,以便猜出传递给函数的正确类型。