无法使用 ctypes (Python) 将参数传递给 dll



在使用ctypes时遇到一些问题

我有一个带有以下界面的测试ll

extern "C"
{
    // Returns a + b
    double Add(double a, double b);
    // Returns a - b
    double Subtract(double a, double b);
    // Returns a * b
    double Multiply(double a, double b);
    // Returns a / b
    double Divide(double a, double b);
}

我还有一个 .def 文件,所以我有"真实"的名字

LIBRARY "MathFuncsDll"
EXPORTS
 Add
 Subtract
 Multiply
 Divide

我可以通过 ctype 从 dll 加载和访问该函数但我无法传递参数,请参阅python输出

>>> from ctypes import *
>>> x=windll.MathFuncsDll
>>> x
<WinDLL 'MathFuncsDll', handle 560000 at 29e1710>
>>> a=c_double(2.12)
>>> b=c_double(3.4432)
>>> x.Add(a,b)
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
    x.Add(a,b)
ValueError: Procedure probably called with too many arguments (16 bytes in excess)
>>> 

但是我可以在没有参数的情况下添加函数?!?!?!?!

>>> x.Add()
2619260

有人可以指出我正确的方向吗?我想忘记一些明显的东西,因为我可以从其他 dll 调用函数(例如 kernel32)

除非另行指定,否则ctypes假定参数为intpointer类型,为返回值假定int类型。 导出的函数通常也默认为 C 调用约定(ctypes 中的 CDLL),而不是 WinDLL。 试试这个:

from ctypes import *
x = CDLL('MathFuncsDll')
add = x.Add
add.restype = c_double
add.argtypes = [c_double,c_double]
print add(1.0,2.5)

输出

3.5

最新更新