2014-03-13 52 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。我在答案中增加了一個明確的註釋。 –