gpt4 book ai didi

python - [ python ] : how to get the string from the pointer by using ctypes?

转载 作者:行者123 更新时间:2023-12-01 06:08:21 26 4
gpt4 key购买 nike

事情是这样的,我使用 windows api EnumWindows 编写了一个程序,它需要一个回调函数作为第一个参数,我的糟糕代码如下:

User32 = WinDLL('User32.dll')
LPARAM = wintypes.LPARAM

HWND = wintypes.HWND
BOOL = wintypes.BOOL

def Proc(hwnd, lparam):
print("hwnd = {}, lparam = {}".format(hwnd, cast(lparam, c_char_p)))
return True

WNDPROCFUNC = WINFUNCTYPE(BOOL, HWND, LPARAM) #用winfunctype 比cfunctype 好
cb_proc = WNDPROCFUNC(Proc)

EnumWindows = User32.EnumWindows
EnumWindows.restype = BOOL

EnumWindows(cb_proc, 'abcd')

然后我运行了该程序,但它只是打印

hwnd = 65820, lparam = c_char_p(b'a')
hwnd = 65666, lparam = c_char_p(b'a')
hwnd = 65588, lparam = c_char_p(b'a')
hwnd = 65592, lparam = c_char_p(b'a')
hwnd = 1311670, lparam = c_char_p(b'a')
hwnd = 591324, lparam = c_char_p(b'a')
hwnd = 66188, lparam = c_char_p(b'a')
hwnd = 393862, lparam = c_char_p(b'a')

为什么不是b'abcd'?

最佳答案

因为您使用的是 Python 3,它将 abcd 视为 ctypes 使用 UTF-16 编码的 Unicode 字符串。但随后您将其转换为假设它是单字节 ANSI 字符串。

您可以通过以下方法之一使程序按照您想要的方式运行:

  1. 使用 Python 2.x
  2. 像这样调用EnumWindows:EnumWindows(cb_proc, b'abcd')
  3. 在以下情况下使用 c_wchar_p:cast(lparam, c_wchar_p)

关于python - [ python ] : how to get the string from the pointer by using ctypes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7023285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com