【发布时间】:2018-12-12 09:10:06
【问题描述】:
为了提供一些背景知识,我使用的是 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 个浮点数作为参数,并在我尝试测试我的 phython/C 接口时将它们打印出来。我的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 中提取第一个列表。
运行此代码后,我能够正确打印字符串,但浮点数似乎是大随机数(1849375168、3、4805786、9397952),而不是_fv[0], _fv[1], _fv[2], _fv[3] 的实际值。因此,为了检查我是否将正确的值传递给calling_function.c_func 函数,我包含了一个打印语句来打印_fv[0], _fv[1], _fv[2], _fv[3] 的值及其类型。我检查了值是浮点数,并且正在将正确的数字输入到函数中,但正在打印出随机数。我以为我可能错误地声明了restype,但我认为restype应该声明为int,因为C代码返回0。
问题1:为什么函数打印出来的是随机数而不是我输入到函数中的浮点数。
问题 2:该函数应该打印出 1 个字符串和 4 个浮点数,所以我应该将 restype 声明为 1 个字符串和 4 个浮点数吗?
我尝试过的事情:
将所有浮点变量更改为双精度值。
将 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 must be a type, a callable, or None.
我不太确定发生了什么。任何帮助将非常感激。谢谢!
【问题讨论】:
-
Ruven Guna,评论stackoverflow.com/help/someone-answers 回滚
标签: python c python-2.7 typeerror ctypes