【问题标题】:Python using the ctypes library with math.h but the answer is always 0Python 将 ctypes 库与 math.h 一起使用,但答案始终为 0
【发布时间】:2020-03-30 13:10:42
【问题描述】:

我想使用 cytypes 来加载 C 共享库 (lib*.so),但我注意到在 C 文件中使用 math.h 后,我无法正确加载它。答案总是 0。这是我共享库中的源代码:

#include <math.h>

double mycos(double num){
   return cos(num);
}

我只是这样构建它:

 gcc -shared -o libtest.so cos.o

这是我的 C 代码来加载它:

#include <stdio.h>

extern double mycos(double num);

int main(){
    printf("%lf",mycos(30));
    return 0;
}

将我的 libtest.so 添加到 /etc/ld.so.conf 后,我运行我的代码:

gcc test.c libtest.so -lm
./a.out

答案是0.154251,是正确答案。

但是,当我在 Python 控制台中运行它时:

>>> from ctypes import *
>>> mylib = CDLL('/home/ubuntu/test/libtest.so')
>>> y=mylib.mycos(30)
>>> y
0

答案是0。我还测试了其他不使用math.h的共享库,答案是正确的。这是怎么发生的?

【问题讨论】:

    标签: python c


    【解决方案1】:

    问题是您需要首先指定argument typesreturn type:ctypes 不知道您的函数期望参数为双精度并且将返回双精度。试试:

    >>> from ctypes import *
    >>> mylib = CDLL('/home/ubuntu/test/libtest.so')
    >>> mylib.mycos.argtypes = [c_double]
    >>> mylib.mycos.restype = c_double
    >>> y=mylib.mycos(30)
    >>> y
    

    没有这些,它将无法正确传递 30 或正确解释响应。 (我猜这个参数实际上是 0,因为 30 最终会出现在双精度尾数的某个位置,并且 cos(0)=1 的结果有四个最低有效字节 0,Python 正在读回一个零 int 结果。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2017-07-15
      • 2013-06-26
      • 2014-01-28
      • 2018-07-08
      相关资源
      最近更新 更多