python - 使用 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 有什么误解?
解决方案
它是拼写的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;
}
推荐阅读
- python - 选择 Pypy 作为 Jupyter 笔记本内核时出错
- javascript - 什么是 CSS 背景:背景?
- javascript - 415 不支持的媒体类型 React Fetch Api
- amazon-web-services - kubectl 从秘密中设置环境
- java - Main 已由 Java 运行时 (Eclipse) 的更新版本编译。运行 JDE 16 代码需要哪个 JRE?
- c - 为什么在 SDL 中渲染纹理时会出现虚假的白色像素?
- redux - 难以实现 redux thunk
- java - 减去单元格值
- python - 从许多文本文件制作 Excel 电子表格
- php - 如何制作一个输出两个数字的阶乘比率(N!/ M!)的脚本?