调用 Python 3 时从 Windows API收到无效句柄

2024-09-27 04:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码在Python2中运行良好:

import ctypes

def test():
    OpenSCManager      = ctypes.windll.advapi32.OpenSCManagerA
    CloseServiceHandle = ctypes.windll.advapi32.CloseServiceHandle

    handle = OpenSCManager(None, None, 0)
    print(hex(handle))
    assert handle, ctypes.GetLastError()
    assert CloseServiceHandle(handle), ctypes.GetLastError()

test()

它在Python 3中不起作用:

^{pr2}$

6表示句柄无效。在

另外,在python2中检索到的句柄似乎是更小的数字,例如0x100ffc0。它不是CloseServiceHandle的特定内容。此句柄不能与任何服务函数一起使用。在

两个Python版本都是64位本机Windows Python。在


Tags: 代码testimportnonedefassertctypes句柄
1条回答
网友
1楼 · 发布于 2024-09-27 04:26:39

您应该使用argtypesrestype,否则所有参数默认为int,并在64位中被截断。{{cd3>你不应该直接调用cd3}代码。在

下面是一个有效的例子:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import ctypes


def test():
    advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
    OpenSCManager = advapi32.OpenSCManagerA
    OpenSCManager.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong]
    OpenSCManager.restype = ctypes.c_void_p

    CloseServiceHandle = advapi32.CloseServiceHandle
    CloseServiceHandle.argtypes = [ctypes.c_void_p]
    CloseServiceHandle.restype = ctypes.c_long

    handle = OpenSCManager(None, None, 0)
    if not handle:
        raise ctypes.WinError(ctypes.get_last_error())
    print(f"handle: {handle:#x}")

    result = CloseServiceHandle(handle)
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())

def main():
    test()


if __name__ == "__main__":
    sys.exit(main())

相关问题 更多 >

    热门问题