2011-08-11 152 views
1

这里是东西,我写了使用Windows API的EnumWindows的一个程序,它需要一个回调FUNC作为第一个参数,我可怜的代码如下:[python]:如何通过使用ctypes从指针获取字符串?

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'?

回答

2

因为您正在使用Python 3将abcd当作Unicode类型的字符串,并且ctypes使用UTF-16进行编码。但是你假设它是一个单字节的ANSI字符串。

可以使程序的行为要通过下列方法之一方法:

  1. 使用Python 2.x的
  2. 呼叫EnumWindows像这样:EnumWindows(cb_proc, b'abcd')
  3. 使用c_wchar_p的情况下: cast(lparam, c_wchar_p)
+0

非常感谢你,它的工作原理。顺便说一句,为什么ctypes使用utf-16编码字符串而不是utf-8?使用utf-8不是很方便吗? – Alcott

+1

@Alcott Windows API使用UTF16而不是UTF8。 –

相关问题