为了提供一些背景知识,我使用的是 linux,并且有如下 C 代码:
int c_func(const char* dir, float a, float b, float c, float d )
{
printf("%s\n", dir);
printf("%f\n",a);
printf("%f\n",b);
printf("%f\n",c);
printf("%f\n",d);
return 0;
}
这是一个简单的函数,它接受一个字符串和 4 个 float 作为参数,并在我尝试测试我的 phython/C 接口(interface)时将它们打印出来。我的python代码如下:
calling_function = ctypes.CDLL("/home/ruven/Documents/Sonar/C interface/Interface.so")
calling_function.c_func.argtypes = [ctypes.c_char_p, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float]
calling_function.c_func.restype = ctypes.c_float
for _fv in _testFV:
_predOut = calling_function.c_func("hello",_fv[0], _fv[1], _fv[2], _fv[3])
exit(1)
澄清一下,_fv[0]、_fv[1]、_fv[2]、_fv[3]
分别是[1.969591, 112.7779, 1.8701470000000002, 111.7575]
. _testFV 是 117 个其他列表的列表。我只是想从 _testFV 中提取第一个列表。
运行此代码后,我能够正确打印字符串,但 float 似乎是较大的随机数 (1849375168、3、4805786、9397952),而不是 _fv[0]、_fv[ 的实际值1], _fv[2], _fv[3]
。因此,为了检查我是否将正确的值传递给 calling_function.c_func
函数,我包含了一个打印语句来打印 _fv[0]、_fv[1]、_fv[2 的值], _fv[3]
及其类型。我检查过,值是 float ,正确的数字被输入到函数中,但随机数被打印出来。我认为我可能错误地声明了 restype,但我认为应该将 restype 声明为 int,因为 C 代码返回 0。
问题一:为什么函数打印的是随机数,而不是我输入函数的 float 。
问题 2:该函数应该打印出 1 个字符串和 4 个 float ,所以我应该将 restype 声明为 1 个字符串和 4 个 float 吗?
我尝试过的事情:
将所有浮点变量更改为 double 。
将 restype 更改为 int 和 double。
将python中
calling_function.c_func
的参数改为("hello",1,2,3,4)
,python中的函数就可以了打印出正确的值。当我将参数更改为 ("hello",1.2,2.3,3.4,4.3) 时,它再次给我随机数。我相信我做错了一些类型声明,但我不确定是什么。将 restype 行更改为
calling_function.c_func.restype = [ctypes.c_char_p, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float]
但这会产生以下错误: TypeError: restype 必须是类型、可调用对象或无。
我不太确定发生了什么。任何帮助将非常感激。谢谢!
最佳答案
对argtypes
使用c_float
对restype
使用c_int
适合我:
foo.c:
int
foo(const char* dir, float a, float b, float c, float d )
{
printf("%s\n", dir);
printf("%f\n", a);
printf("%f\n", b);
printf("%f\n", c);
printf("%f\n", d);
return 0;
}
使用 Python 2.7:
>>> f = ctypes.CDLL('./foo.so')
>>> f.foo.argtypes = [ctypes.c_char_p, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float]
>>> f.foo.restype = ctypes.c_int
>>> f.foo('hello', 1.0, 1.1, 1.2, 1.3)
hello
1.000000
1.100000
1.200000
1.300000
0
>>>
关于python - Ctypes将float传递给函数返回随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164980/