ctypes包装的“MessageBoxA”示例在python33中不起作用

2024-09-24 08:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这个例子在python 3.3.2文档中:

http://docs.python.org/3/library/ctypes.html?highlight=ctypes#ctypes

但是:当我在翻译中尝试时,我得到了一个错误。在

我使用windows732python3.3.2。在

请帮忙。在

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2, text="foo bar")

error message:
Traceback (most recent call last):
File "<string>", line 250, in run_nodebug
File "<g1>", line 7, in <module>
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type

Tags: textfromimportspamctypesintflagsprototype
1条回答
网友
1楼 · 发布于 2024-09-24 08:34:04

我猜这是文档中的一个bug。;—)

在python3中,默认情况下,所有的字符串都是Unicode,但是这个例子调用的是ANSI MessageBoxA函数,而不是MessageBoxWUnicode版本。请参见ctypes文档中的16.17.1.2. Accessing functions from loaded dlls。在

{{cd5>在cd5>函数中调用{1>的参数可以得到什么结果:

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
import locale
preferred_encoding = locale.getpreferredencoding(False)
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = ((1, "hwnd", 0), (1, "text", "Hi".encode(preferred_encoding)),
                (1, "caption", None), (1, "flags", 0))
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

MessageBox()
MessageBox(text="Spam, spam, spam".encode(preferred_encoding))
MessageBox(flags=2, text="foo bar".encode(preferred_encoding))

使用支持“宽”Unicode字符串参数(LPCWSTR而不是LPCSTR)的MessageBoxWWindows函数,这样就不必在几乎每次调用中显式编码它们。此外,我将用命名常量替换示例中的大多数“幻数”:

^{pr2}$

相关问题 更多 >