Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
[python]:如何使用ctypes从指针获取字符串?_Python_Pointers_Ctypes - Fatal编程技术网

[python]:如何使用ctypes从指针获取字符串?

[python]:如何使用ctypes从指针获取字符串?,python,pointers,ctypes,Python,Pointers,Ctypes,事情是这样的,我使用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

事情是这样的,我使用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
视为Unicode字符串,ctypes使用UTF-16编码。但是,假设它是一个单字节的ANSI字符串,则将其强制转换

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

  • 使用Python2.x
  • 调用
    EnumWindows
    像这样:
    EnumWindows(cb_proc,b'abcd')
  • 在下列情况下使用
    c\u wchar\u p
    :cast(lparam,c\u wchar\u p)

  • 非常感谢,它很有效。顺便问一下,为什么ctypes用utf-16而不是utf-8编码字符串?使用utf-8不是很方便吗?@Alcott Windows API使用UTF16而不是UTF8。