gpt4 book ai didi

python - 使用 Python C 类型在 kernel32 上调用 GetModuleHandle

转载 作者:行者123 更新时间:2023-12-02 11:30:38 24 4
gpt4 key购买 nike

我正在尝试使用 Python 的 C 类型来调用 kernel32 库上的 GetModuleHandleA。我想获得该库的句柄,以便我可以使用它来调用 LoadLibraryA 的 GetProcAddress。下面是我的代码...

import sys
from ctypes

kernel32 = windll.kernel32
print("The kernel32 is %s" % kernel32)
#The kernel32 is <WinDLL 'kernel32', handle 765b0000 at 1c2a9f0>

h_kernel32 = kernel32.GetModuleHandleA("C:\\Windows\\System32\\kernel32.dll")
if h_kernel32 == False:
error = GetLastError()
print("ERROR: %d - %s" % (error, FormatError(error)))

我收到错误“错误:126 - 找不到指定的模块”。我还尝试过“C:/Windows/System32/kernel32.dll”和“kernel32”。我正在使用 Python 3.2,这是在 Windows 7 计算机上。我已经验证该 dll 存在并且位于我在上面代码中设置的路径中。我一直在做一些研究,似乎无法找出问题所在。任何帮助是极大的赞赏。谢谢!

最佳答案

句柄存储在kernel32._handle中。调用 GetModuleHandle 应返回相同的值,但请确保设置 restypeargtypes 以实现类型安全 [*]:

import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

kernel32.GetModuleHandleW.restype = wintypes.HMODULE
kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]

hMod = kernel32.GetModuleHandleW('kernel32.dll')

请注意“W”后缀而不是“A”。 Python 3 使用 Unicode 字符串,ctypes 为其创建一个 c_wchar_p (LPCWSTR)。没有理由调用 [A]NSI 版本,因为它只是 [W]ide 字符串版本的包装器。但如果你必须,那么你需要使用字节:

kernel32.GetModuleHandleA.restype = wintypes.HMODULE
kernel32.GetModuleHandleA.argtypes = [wintypes.LPCSTR]

hMod = kernel32.GetModuleHandleA(b'kernel32.dll')
<小时/>

[*] 我建议使用 kernel32 = WinDLL('kernel32', use_last_error=True) 而不是 windll.kernel32。这可以避免与使用 windll 的其他模块发生冲突。它还可以保护线程的LastErrorValue。在这种情况下,请使用 ctypes.get_last_error()ctypes.set_last_error(err) 而不是直接调用 WinAPI GetLastErrorSetLastError.

关于python - 使用 Python C 类型在 kernel32 上调用 GetModuleHandle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17033733/

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