【问题标题】:Ctypes returns wrong ResultCtypes 返回错误的结果
【发布时间】: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 函数的返回值始终为零。 我没有看到错误,有什么想法吗?

【问题讨论】:

    标签: python c ctypes


    【解决方案1】:

    改变这个:

    lib.add_numbers.restypes = [c_double]
    

    到这里:

    lib.add_numbers.restype = c_double
    

    注意是restype,而不是restypes

    【讨论】:

    • 这没什么区别
    • 谢谢@eryksun。我在答案中添加了关于该更改的明确说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多