Python Ctypes返回错误的结果
i尝试使用ctypes包装c函数,例如:Python Ctypes返回错误的结果,python,c,ctypes,Python,C,Ctypes,i尝试使用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; } 到共享库 Python代码如下所示: from ctypes import
#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;
}
到共享库
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函数的返回值始终为零。
我看不出错误,知道吗 改变这一点:
lib.add_numbers.restypes = [c_double]
为此:
lib.add_numbers.restype = c_double
请注意,它是
重新类型
,而不是重新类型
,这与hanks@eryksun没有任何区别。我在答案中添加了一个明确的注释。
lib.add_numbers.restype = c_double