我正在连接这个 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调用约定进行编译。