Ctypes返回错误结果

3

我想用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

这没有任何区别 - jrsm
感谢@eryksun。我在答案中添加了一个明确的注释关于那个变化。 - Warren Weckesser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接