簡體   English   中英

Ctypes將float傳遞給函數返回隨機數

[英]Ctypes pass float into function returns random numbers

為了提供一些背景信息,我使用的是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]_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]的實際值_fv[0], _fv[1], _fv[2], _fv[3] 因此,要檢查我是否將正確的值傳遞給calling_function.c_func函數,我包括了一條打印語句,以打印_fv[0], _fv[1], _fv[2], _fv[3]及其類型。 我檢查了一下,這些值是浮點型的,正確的數字正在輸入到函數中,但隨機數正在打印出來。 我以為我可能錯誤地聲明了retype,但是我認為當C代碼返回0時,應該將restype聲明為int。

問題1:為什么函數會打印出隨機數而不是我輸入到函數中的浮點數。

問題2:該函數應該輸出1個字符串和4個浮點數,所以我應該將restype聲明為1個字符串和4個浮點數嗎?

我嘗試過的事情:

  1. 將所有float變量更改為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必須為類型,可調用或沒有。

我不太確定發生了什么。 任何幫助將非常感激。 謝謝!

使用c_floatargtypesc_intrestype為我工作:

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
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM