python - Python中调用C函数的问题

标签 python c types

我想通过 Python 调用一个用 C 编写的函数。为此,我在目录中创建了三个文件:

csquare.c
csquare.so
script.py

名为 csquare.c 的文件:

#include <stdio.h>
double math_square(double x) {
     return x*x;
 }

脚本.py:

import ctypes
import os

def Main():
    os.system('cc -fPIC -shared -o csquare.so csquare.c')
    so_path = str(os.getcwd()) + '/csquare.so'
    cfunctions = ctypes.CDLL(so_path)
    cfunctions.math_square.argtypes = [ctypes.c_double]

    print(cfunctions.math_square(90.0))

if __name__ == "__main__":
    Main()

问题是程序总是打印“1”。我究竟做错了什么?如果我将 math_square 函数的类型更改为 "int" 一切正常。

提前致谢

最佳答案

这在您的 python 源代码中缺失:

cfunctions.math_square.restype = ctypes.c_double

默认的返回类型是ctypes.c_int:

https://docs.python.org/3/library/ctypes.html#return-types

关于python - Python中调用C函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65054379/

相关文章:

python - 具有间隙的信号的功率谱密度?

python - 将字符串拆分为字母和数字

c - 数据类型和格式说明符

c - 仅 Unix 编译器的错误消息

flash - 可以返回两种类型的方法的 AS3 最佳实践

python - 在 AJAX 请求中包含 Bottle 模板

python - 索引 38 超出轴 1 的范围,尺寸为 38 - Sklearn

c - Travis-CI 上的 GTK2 链接错误

types - 在 F# 中定义非零整数类型

python - 将参数从 Python 传递到 C 时出现问题