我有一个C扩展名,我通过ctypes在python中调用。C代码如下所示:
double new(int t){
double sum;
sum = (double)t*(double)1.5;
return sum;
}
像这样的Python代码:
import ctypes
fun = ctypes.CDLL("C:/test.so")
fun.new.argtypes = [ctypes.c_int]
fun.new.restypes = ctypes.c_double
fun.new(2)
因此,人们希望输出为“ 3.0”,但我得到的输出为“ -1398886288”。我将其分解为一个简单的示例。我的实际应用程序要大得多,但在那里我也得到了一些奇怪的输出。也许我对ctypes有误?
它的拼写是restype
,而不是restypes
:
fun.new.restype = ctypes.c_double
通过此更改,代码“有效”。但是它会缩放数字,不会计算出``和''。它还包含不必要的强制转换,并且不必要地拆分了声明和初始化。
以下通常被视为实现此功能的首选方法:
double three_halves(int x) {
double result = x * 1.5;
return result;
}
或者,如果实际上是该功能的全部,请省略不必要的中间变量:
double three_halves(int x) {
return x * 1.5;
}