ctypes MessageBoxW返回意外的中文字符

时间:2019-02-17 06:30:22

标签: python windows ctypes

我使用以下代码显示弹出消息

if platform.system() == 'Windows':
    import ctypes

    def message_box(title, text, style):
        return ctypes.windll.user32.MessageBoxW(0, text, title, style)

if platform.system() == 'Windows':
    message_box('Error', 'Phat sinh loi Unicode, kiem tra chi tiet trong %s' % common.ERR_LOG_FILE, 0)

当我的应用程序在Windows 7中运行时,弹出窗口包含所有意外的中文字符,而我的原始消息(在代码段中)仅包含字母字符。这是我第一次使用ctypes并且很困惑。 有人请解释并帮助我解决它。

popup result

2 个答案:

答案 0 :(得分:2)

我猜您正在使用Python2。Python2的字符串是字节字符串,并封送为字节字符串(char*)。 Python 3的字符串是Unicode字符串,并被编组为宽字符串(wchar_t*)。如果不定义.argtypesctypes将不会进行错误检查并愉快地传递错误的类型。

要在Python 2上调用MessageBoxW,请改用Unicode字符串,但是最好定义.argtypes.restype,以便ctypes可以键入check并告诉您何时参数错误:

#python2
import ctypes
from ctypes import wintypes as w

user32 = ctypes.WinDLL('user32')
MessageBox = user32.MessageBoxW
MessageBox.argtypes = w.HWND,w.LPCWSTR,w.LPCWSTR,w.UINT
MessageBox.restype = ctypes.c_int

MessageBox(None, u'message', u'title', 0)

答案 1 :(得分:0)

我亲自修复了它:

def message_box(title, text, style=0):
    return ctypes.windll.user32.MessageBoxW(0, unicode(text), unicode(title), style)