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

4
有些问题使用ctypes
我有一个测试dll,其接口如下:
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)调用函数。

1
几点建议:(1)尝试添加 x.Add.restype = c_double(以及类似的内容),以便您的函数返回除 int 之外的任何内容-请参见http://docs.python.org/library/ctypes.html#return-types。(2)您是否尝试指定函数参数的类型(http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes)? (3)您是否在64位Python上加载32位DLL,还是在32位Python上加载64位DLL? - Luke Woodward
1个回答

8

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

1
使用WinDLL没有起作用,我还需要argtypes参数。请提供必要的两个提示,谢谢。 - nobs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接