【发布时间】:2014-03-13 21:23:36
【问题描述】:
f我尝试使用 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 函数的返回值始终为零。 我没有看到错误,有什么想法吗?
【问题讨论】: