ctypes如何推断传递的整数类型?

How can ctypes infer the types of integers that are passed?

我正在连接这个 C 代码:

extern "C" void print_int(short a, int b, long c, long long d)
{
   printf("%hi %i %li %lli", a, b, c, d);
}

使用此 Python 代码:

from ctypes import *
lib=cdll.LoadLibrary("./libtest.so")
lib.print_int(1,2,3,4)

即使我不在 print_int 代码中转换参数,它们也会正确传递,我得到:

1 2 3 4

符合预期。为什么 ctypes 不能做相同形式的浮点数?以下片段:

extern "C" void print_float(float a, double b, long double c)
{
   printf("%f %lf %Lf", a, b, c);
}

需要从 ctypes 进行显式转换,否则会引发异常。

lib.print_float(c_float(1.0), c_double(2.0), c_longdouble(3.0))

我在 Unix 中工作,如果重要的话,使用 cdecl 调用约定进行编译。

因为默认值和堆栈大小。如果您不指定类型,ctypes 将假定为 c_int。在 64 位系统上,堆栈是 64 位的,因此 shorts、ints、longs、long longs 都是符号扩展并使用 64 位堆栈槽。 long long 在 32 位系统上会中断。 float 是一种完全不同的二进制格式,与 c_int.

不兼容

您可以使用.argtypes指定参数类型,然后正常传值。另外 .restype 指定 return 值:

lib.print_float.argtypes = c_float,c_double,c_longdouble
lib.print_float.restype = None
lib.print_float(1,2,3)