Here is the thing, I wrote a program using windows api EnumWindows which requires a callback func as the first arg, my poor code is as follows:
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')
then I ran the program, but it just print
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')
why not b’abcd’?
Because you are using Python 3 which is treating
abcdas a Unicode string which ctypes encodes with UTF-16. But you then cast it assuming it is a single byte ANSI string.You can make the program behave the way you want by one of the following methods:
EnumWindowslike so:EnumWindows(cb_proc, b'abcd')c_wchar_pin the case:cast(lparam, c_wchar_p)