【发布时间】:2020-02-24 20:45:06
【问题描述】:
我用 C 语言编写了一个简单的函数,可以将给定的数字提高到给定的幂。当我在 C 中调用它时,该函数返回正确的值,但是当我在 Python 中调用它时,它返回一个不同的、不正确的值。
我使用以下命令创建了共享文件:
$ gcc -fPIC -shared -o test.so test.c
我尝试了 C 函数的不同配置,其中一些返回预期值,而另一些则不返回。例如,当我的函数是一个使用return x*x 的简单正方形时,没有for 循环,它在Python 中返回正确的值。
我希望最终能够在python中调用一个返回二维C数组的C函数。
#include <stdio.h>
float power(float x, int exponent)
{
float val = x;
for(int i=1; i<exponent; i++){
val = val*x;
}
return val;
}
from ctypes import *
so_file = '/Users/.../test.so'
functions = CDLL(so_file)
functions.power.argtype = [c_float, c_int]
functions.power.restype = c_float
print(functions.power(5,3))
当我在C中调用函数时,我得到预期的输出125.0,但是当我在python中调用该函数时,它返回的值是0.0。
这是我第一次使用 ctypes。我是否犯了一个明显的错误导致函数计算错误?
【问题讨论】:
-
argtypes(以s结尾)。 python docs