Python ctypes 和参数不足(缺少4字节)

4 投票
3 回答
7513 浏览
提问于 2025-04-15 14:30

我想调用的函数是:

void FormatError (HRESULT hrError,PCHAR pszText);

这个函数来自一个自定义的动态链接库(dll),我使用的是windll。

c_p = c_char_p()
windll.thedll.FormatError(errcode, c_p)

结果是:

ValueError: Procedure probably called with not enough arguments (4 bytes missing)

如果我用cdll的话,缺失的字节计数会增加到12。上面的errcode是从同一个dll的另一个函数返回的错误代码。我该怎么正确调用这个函数呢?

3 个回答

0

其实我觉得你应该使用ctypes提供的FormatError。

http://docs.python.org/library/ctypes.html#ctypes.FormatError

ctypes.FormatError([code])

这个功能只在Windows系统上可用:它会返回一个错误代码的文字描述。如果你没有指定错误代码,它会使用最后一个错误代码,这个代码是通过调用Windows的api函数GetLastError获得的。

0

你有没有试过使用 ctypes.HRESULT 呢?

2

至少,如果你正确设置了 argtypesrestype,你会得到更清晰的错误信息。

试试这样做:

windll.thedll.FormatError.argtypes = [ctypes.HRESULT, ctypes.c_char_p]
windll.thedll.FormatError.restype  = None

你很可能使用了错误的调用约定——可以查看 调用函数部分加载库部分,了解如何使用不同的调用约定。

撰写回答