python - Ctypes将float传递给函数返回随机数

标签 python c python-2.7 typeerror ctypes

为了提供一些背景知识,我使用的是 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 吗?

我尝试过的事情:

  1. 将所有浮点变量更改为 double 。

  2. 将 restype 更改为 int 和 double。

  3. 将python中calling_function.c_func的参数改为("hello",1,2,3,4),python中的函数就可以了打印出正确的值。当我将参数更改为 ("hello",1.2,2.3,3.4,4.3) 时,它再次给我随机数。我相信我做错了一些类型声明,但我不确定是什么。

  4. 将 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_floatrestype 使用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/

相关文章:

python - 在 Gurobi/Python 中获取并比较变量值

python - 返回动态生成的文件而不创建 tmp 版本?

python - 如何遍历 pandas 组并检查每个组中是否有字符串?

python - Django & Redis : How do I properly use connection pooling?

c - 为什么这对别人有效,对我却无效?

c - 对称多处理和分布式系统?

python - UnicodeDecodeError : 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

c - 多维数组中的字符串没有终止 NUL 字符?

python - 动态调用方法名?

python - python字典中的求和