2

当我尝试从内核库调用任何函数时,在 python 3.4.3 和 2.7.9 中。

在 64 位 Windows 上从 32 位版本的 python 打印错误消息:

from ctypes import *
path=create_string_buffer(256) 
rs=cdll.Kernel32.GetModuleFileNameA(0,path,256)
print (path)

错误如下:

Traceback (most recent call last):
      File "test-ctypes.py", line 3, in <module>
      ValueError: Procedure called with not enough arguments (12 bytes missing) or wrong calling convention
4

1 回答 1

4

异常信息告诉你答案:

ValueError: 调用的过程没有足够的参数(缺少 12 个字节)或错误的调用约定

参数的数量是正确的,所以它必须是另一个:您使用了错误的调用约定。调用约定是编译器将 C 中的三个参数映射为一种在调用函数时将实际值存储在内存中的方式(以及其他一些事情)。在GetModuleFileA 的 MSDN 文档中,您可以找到以下签名

DWORD WINAPI GetModuleFileName(
  _In_opt_ HMODULE hModule,
  _Out_    LPTSTR  lpFilename,
  _In_     DWORD   nSize
);

WINAPI告诉编译器使用调用stdcall约定。cdll另一方面,您的 ctypes 代码使用假定cdecl调用对流。解决方案很简单:更改cdllwindll

from ctypes import *
path=create_string_buffer(256) 
rs=windll.Kernel32.GetModuleFileNameA(0,path,256)
print (path)

与访问 .dll 的 ctypes 文档进行比较,其中kernel32明确显示使用windll.

于 2015-05-20T07:49:16.900 回答