[英]Function always returns meaningless value
我正在編寫c函數,由cffi在pypy3中調用。 但是,無論真正的返回值是什么,包裝函數總是在pypy3中返回無意義的值。
printf()
函數的輸出告訴我C函數中的一切正常,但pypy3中的返回值已更改。
C函數是這樣寫的:
double test(){
return 5.12;
}
double test2(){
double tmp=test();
printf("!!!!!!!%f\n",tmp);
return tmp;
}
cffi構建腳本如下:
from cffi import FFI
ffibuilder = FFI()
ffibuilder.set_source("_faststr_cffi",
"""
#include <Python.h>
#include "stdint.h"
#include <string.h>
typedef uint32_t char32_t;
""",
sources=['faststr_purec.c']
) # library name, for the linker
ffibuilder.cdef("""
double test();
double test2();
""")
if __name__ == "__main__":
ffibuilder.compile(verbose=True)
我試着在pypy3控制台中調用test2():
>>>> from _faststr_cffi import lib
>>>> lib.test2()
!!!!!!!5.120000
16.0
printf告訴我返回值應該是5.120000,但它在pypy3中返回16.0。
我找到了一些線索:如果我在test2()printf函數中更改了字符串,則更改pypy3中test2的返回值。
更新:cpython 3.6.7中的結果是相同的,因此它不是pypy3問題
問題如下:
在這里,您聲明函數test()
和test2()
:
ffibuilder.cdef("""
double test();
double test2();
""")
這些聲明僅適用於cffi接口,以了解要使用的返回值。 但缺少原生c函數test()
和test2()
的聲明。 因此,它們被隱式聲明返回int
!
現在從test2調用函數test()
(隱式聲明返回int)
double tmp = test();
return tmp;
已編譯的代碼讀取錯誤的寄存器 (因為它查找整數值)並將其轉換為double,因此返回它。 碰巧,最后一個整數結果是printf()
的結果,它是打印字符串的長度。 因此,在您的情況下,您將獲得16
的結果。
修復是,正確聲明函數test()
和test2()
:
ffibuilder.set_source("_faststr_cffi",
"""
#include <Python.h>
#include "stdint.h"
#include <string.h>
typedef uint32_t char32_t;
double test();
double test2();
""",
sources=['faststr_purec.c']
) # library name, for the linker
然后它應該按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.