【问题标题】:How can ctypes infer the types of integers that are passed?ctypes 如何推断传递的整数类型?
【发布时间】:2019-10-22 21:14:51
【问题描述】:

我正在连接这个 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 不能做同样形式的浮点数?以下sn-p:

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 调用约定进行编译。

【问题讨论】:

    标签: python ctypes cdecl


    【解决方案1】:

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

    可以使用.argtypes指定参数类型,然后正常传值。还有.restype指定返回值:

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

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2018-10-15
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多