Ctypes 返回错误结果
我尝试用ctypes来封装一个C语言的函数,比如:
#include<stdio.h>
typedef struct {
double x;
double y;
}Number;
double add_numbers(Number *n){
double x;
x = n->x+n->y;
printf("%e \n", x);
return x;
}
我用这个选项来编译C文件:
gcc -shared -fPIC -o test.so test.c
生成一个共享库。
然后Python代码是这样的:
from ctypes import *
class Number(Structure):
_fields_=[("x", c_double),
("y", c_double)]
def main():
lib = cdll.LoadLibrary('./test.so')
n = Number(10,20)
print n.x, n.y
lib.add_numbers.argtypes = [POINTER(Number)]
lib.add_numbers.restypes = [c_double]
print lib.add_numbers(n)
if __name__=="__main__":
main()
在add_numbers函数里的printf语句返回了预期的值3.0e+1,但lib.add_numbers函数的返回值总是零。我看不出哪里出错了,有什么想法吗?
1 个回答
9
把这个:
lib.add_numbers.restypes = [c_double]
改成这个:
lib.add_numbers.restype = c_double
注意是 restype
,而不是 restypes
。