执行windll.version.GetFileVersionInfoSizeA()在Python3中失败

2024-06-08 08:22:04 发布

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

我正在尝试用python ctypes执行windll.version.GetFileVersionInfoSizeA()。我正在执行以下代码:

_GetFileVersionInfoSizeA = ctypes.windll.version.GetFileVersionInfoSizeA
_GetFileVersionInfoSizeA.argtypes = [ctypes.c_char_p, ctypes.c_void_p]
_GetFileVersionInfoSizeA.restype = ctypes.c_uint32
_GetFileVersionInfoSizeA.errcheck = RaiseIfZero # RaiseIfZero is a function to raise error
# lptstrFilename is the file path
dwLen = _GetFileVersionInfoSizeA(lptstrFilename, None)

这段代码在Python2中运行得非常好,但在Python3.8中不起作用。它给出以下错误:

argument 1: <class 'TypeError'>: wrong type

根据msdn docfor GetFileVersionInfoSizeA,第二个参数应该是:

"A pointer to a variable that the function sets to zero."


我尝试了下面的代码,但它给出了与以前相同的错误。你知道吗

dwLen = _GetFileVersionInfoSizeA(lptstrFilename, LPVOID)

我不知道我错过了什么。
注意-这是我第一次使用ctypes。你知道吗


Tags: theto代码isversion错误functionctypes
2条回答

在Python中,3个字符串默认为Unicode。即使在Python2中,使用Unicode字符串也是最好的,因此Windows API的W版本也是Unicode。所以要严格按照文档调用API:

>>> from ctypes import *
>>> from ctypes import wintypes as w
>>> dll = WinDLL('api-ms-win-core-version-l1-1-0')
>>> GetFileVersionInfoSize = dll.GetFileVersionInfoSizeW
>>> GetFileVersionInfoSize.argtypes = w.LPCWSTR,w.LPDWORD
>>> GetFileVersionInfoSize.restype = w.DWORD
>>> GetFileVersionInfoSize('test.exe',byref(w.DWORD())) # create a temporary DWORD passed by reference.
2316

注意,第二个参数没有被记录为接受nullptr(Python中的a.k.aNone),因此它应该是一个有效的引用。你知道吗

要调用函数的ANSI(A)版本,请传递一个以默认ANSI编码正确编码的字节字符串,例如'test.exe'.encode('ansi'),但请注意,非ASCII文件名会引起麻烦,使用Unicode(W)版本可以减轻这种麻烦。你知道吗

在python2中,可以使用两种类型来表示字符串。字符串Unicode字符串。因此c_char_pctypes类型用于表示python2字符串类型c_wchar_pctypes类型用于表示python2 Unicode字符串类型。你知道吗

但是在python3中只有一种字符串类型。因此,c_wchar_pctypes类型用于表示python3string类型,c_char_pctypes类型用于表示python3bytes类型。你知道吗

您可以在^{}^{}文档中找到基本的数据类型。你知道吗

所以你可以

dwLen = _GetFileVersionInfoSizeA(your_file_name.encode(), None)

相关问题 更多 >