2014-03-13 53 views
0

网络连接尝试使用ctypes的包装C函数,例如:ctypes的返回错误结果

#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函数的返回值始终为零。 我没有看到错误,任何想法?

回答

5

更改此:

lib.add_numbers.restypes = [c_double] 

这样:

lib.add_numbers.restype = c_double 

请注意,这是restype,不restypes

+0

这没有什么区别 – jrsm

+0

谢谢你,完全忽略了这个... – jrsm

+0

谢谢@eryksun。我在答案中增加了一个明确的注释。 –