首页 > 解决方案 > 使用 C 和 ctypes 计算的奇怪行为

问题描述

我有一个 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 有什么误解?

标签: pythoncctypes

解决方案


它是拼写的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;
}

推荐阅读