【问题标题】:ctypes in Python 2.6 helpPython 2.6 中的 ctypes 帮助
【发布时间】:2009-06-17 04:26:50
【问题描述】:

我似乎无法让这段代码工作,我的印象是我做对了。

from ctypes import *


kernel32 = windll.kernel32

string1 = "test"
string2 = "test2"

kernel32.MessageBox(None,
                       string1,
                       string2,
                       MB_OK)

** 我尝试按照下面的建议将其更改为 MessageBoxA ** ** 我得到的错误 :: **

Traceback (most recent call last):
  File "C:\<string>", line 6, in <module>
  File "C:\Python26\Lib\ctypes\__init__.py", line 366, in __getattr__
    func = self.__getitem__(name)
  File "C:\Python26\Lib\ctypes\__init__.py", line 371, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'MessageBoxA' not found

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

    MessageBox 是在 user32 而不是 kernel32 中定义的,你也没有定义 MB_OK 所以改用这个

    windll.user32.MessageBoxA(None, string1, string2, 1)
    

    另外我建议使用python win32 API 代替它,因为它具有所有常量和命名函数

    编辑:我的意思是使用这个

    from ctypes import *
    
    kernel32 = windll.kernel32
    
    string1 = "test"
    string2 = "test2"
    
    #kernel32.MessageBox(None, string1, string2, MB_OK)
    windll.user32.MessageBoxA(None, string1, string2, 1)
    

    你可以使用 win32 api 做同样的事情

    import win32gui
    win32gui.MessageBox(0, "a", "b", 1)
    

    【讨论】:

    • 我的意思是你使用了错误的 dll,看到我已经用改变的行再次输入了整个代码
    • 哦,我说的是win32 api,我没有意识到这是一个链接:pp
    【解决方案2】:

    问题是您尝试调用的函数实际上并未命名为MessageBox()。有两个函数,名为MessageBoxA()MessageBoxW():前者采用 8 位 ANSI 字符串,后者采用 16 位 Unicode(宽字符)字符串。在 C 中,预处理器符号 MessageBox#defined,可以是 MessageBoxAMessageBoxW,这取决于是否启用了 Unicode(特别是,如果定义了符号 _UNICODE)。

    其次,根据MessageBox() documentationMessageBoxA/W位于user32.dll,而不是kernel32.dll

    试试这个(我无法验证,因为我现在不在 Windows 机器前):

    user32 = windll.user32
    user32.MessageBoxA(None, string1, string2, MB_OK)
    

    【讨论】:

      【解决方案3】:

      哦,任何时候你都对调用是否需要 kernel32 或 user32 或类似的东西感到困惑。不要害怕在 MSDN 上寻找电话。他们有一个Alphabetical List 和一个基于categories 的列表。 希望它们对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2011-03-11
        • 1970-01-01
        • 2011-05-15
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 2011-06-10
        相关资源
        最近更新 更多