You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用C语言double类型函数返回值异常问题求助

问题分析与解决:Python调用C double函数返回值异常

嘿,这个问题我之前也碰到过!核心原因是你没有给ctypes指定C函数的返回值类型——ctypes默认会把所有C函数的返回值当作int类型处理,但你的math_square返回的是double,这种类型不匹配直接导致了返回值被错误解析,最终输出了不符合预期的1。当你把函数改成返回int时,默认的返回值类型刚好匹配,所以结果就正常了。

解决方法很简单:

只需要在Python代码中给math_square函数指定返回值类型为ctypes.c_double,告诉ctypes该如何正确解析返回的二进制数据。

修改后的script.py代码如下:

import ctypes
import os
def Main():
    os.system('cc -fPIC -shared -o csquare.so csquare.c')
    so_path = os.path.join(os.getcwd(), 'csquare.so')  # 用os.path.join更安全跨平台
    cfunctions = ctypes.CDLL(so_path)
    # 指定输入参数类型
    cfunctions.math_square.argtypes = [ctypes.c_double]
    # 新增:指定返回值类型
    cfunctions.math_square.restype = ctypes.c_double
    print(cfunctions.math_square(90.0))
if __name__ == "__main__":
    Main()

为什么之前会输出1?

当你不指定restype时,ctypes强制把double类型的返回值(这里是8100.0)当作int来读取。double和int的内存布局完全不同,这种错误的解析在你的环境里刚好得到了1——这其实是个随机的错误值,不同平台可能会有不同结果。指定restype后,ctypes就会按照double的格式去解析返回的二进制数据,自然就能得到正确的8100.0了。

额外小建议:

你现在每次运行Python脚本都会重新编译一次.so文件,其实可以加个判断,只有当csquare.so不存在或者csquare.c有更新时再编译,这样能提升运行效率:

import ctypes
import os
import time

def Main():
    so_file = 'csquare.so'
    c_file = 'csquare.c'
    # 检查是否需要重新编译
    if not os.path.exists(so_file) or \
       os.path.getmtime(c_file) > os.path.getmtime(so_file):
        os.system('cc -fPIC -shared -o {} {}'.format(so_file, c_file))
    
    so_path = os.path.join(os.getcwd(), so_file)
    cfunctions = ctypes.CDLL(so_path)
    cfunctions.math_square.argtypes = [ctypes.c_double]
    cfunctions.math_square.restype = ctypes.c_double
    print(cfunctions.math_square(90.0))

if __name__ == "__main__":
    Main()

内容的提问来源于stack exchange,提问作者Kojumbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:34:19