我想通过 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
:
关于python - Python中调用C函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65054379/