Python 3.4上的GetProcAddress奇怪行为
在Python 2.7.10上:Python 3.4上的GetProcAddress奇怪行为,python,python-2.7,python-3.x,winapi,ctypes,Python,Python 2.7,Python 3.x,Winapi,Ctypes,在Python 2.7.10上: >>> from ctypes import windll >>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleA('kernel32'), 'LoadLibraryW') 返回非空结果。但是在Python3.X上,同样的结果总是返回null >>> from ctypes import windll >>>
>>> from ctypes import windll
>>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleA('kernel32'), 'LoadLibraryW')
返回非空结果。但是在Python3.X上,同样的结果总是返回null
>>> from ctypes import windll
>>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleA('kernel32'), 'LoadLibraryA')
0
# and other variants
>>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleA('kernel32'), 'LoadLibraryW')
0
>>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleW('kernel32'), 'LoadLibraryA')
0
>>> windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleW('kernel32'), 'LoadLibraryW')
0
有什么问题以及如何修复(如果可能的话)
GetProcAddress
在处理函数名字符串方面有点不寻常。由于导出的函数名始终使用8位文本编码,因此过程名参数的类型为LPCSTR
Python 2.7字符串类型str
不是Unicode,当传递到ctypes
时,默认将文本编码为8位。Python3.x字符串类型是Unicode,当传递到ctypes
时,默认将文本编码为16位。因此失败了
使用argtypes
和restype
精确定义类型并解决此问题
>>> from ctypes import * # just for this answer, to save typing
>>> GetModuleHandle = windll.kernel32.GetModuleHandleW
>>> GetModuleHandle.argtypes = [c_wchar_p]
>>> GetModuleHandle.restype = c_void_p
>>> kernel32 = GetModuleHandle('kernel32')
>>> kernel32
2004418560
>>> 2004418560
2004418560
>>> GetProcAddress = windll.kernel32.GetProcAddress
>>> GetProcAddress.argtypes = [c_void_p, c_char_p]
>>> GetProcAddress.restype = c_void_p
>>> LoadLibraryW = GetProcAddress(kernel32, b'LoadLibraryW') # force 8 bit encoding
>>> LoadLibraryW
2004509856
>>>从ctypes import*#仅针对此答案,保存键入
>>>GetModuleHandle=windell.kernel32.GetModuleHandleW
>>>GetModuleHandle.argtypes=[c\u wchar\u p]
>>>GetModuleHandle.restype=c\u void\u p
>>>kernel32=GetModuleHandle('kernel32')
>>>内核32
2004418560
>>> 2004418560
2004418560
>>>GetProcAddress=windell.kernel32.GetProcAddress
>>>GetProcAddress.argtypes=[c\u void\u p,c\u char\u p]
>>>GetProcAddress.restype=c\u void\u p
>>>LoadLibraryW=GetProcAddress(内核32,b'LoadLibraryW')#强制8位编码
>>>装载库
2004509856
谢谢你的解释!它的作用是:windl.kernel32.GetProcAddress(windl.kernel32.GetModuleHandleW('kernel32'),b'LoadLibraryW')